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
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/scripts/rlgames_demo.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. 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. # # 3. Neither the name of the copyright holder 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 WARRANTIES, 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, INDIRECT, 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. from swervesim.utils.hydra_cfg.hydra_utils import * from swervesim.utils.hydra_cfg.reformat import omegaconf_to_dict, print_dict from swervesim.utils.demo_util import initialize_demo from swervesim.utils.config_utils.path_utils import retrieve_checkpoint_path from swervesim.envs.vec_env_rlgames import VecEnvRLGames from swervesim.scripts.rlgames_train import RLGTrainer import hydra from omegaconf import DictConfig import datetime import os import torch class RLGDemo(RLGTrainer): def __init__(self, cfg, cfg_dict): RLGTrainer.__init__(self, cfg, cfg_dict) self.cfg.test = True @hydra.main(config_name="config", config_path="../cfg") def parse_hydra_configs(cfg: DictConfig): time_str = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") headless = cfg.headless env = VecEnvRLGames(headless=headless, sim_device=cfg.device_id) # ensure checkpoints can be specified as relative paths if cfg.checkpoint: cfg.checkpoint = retrieve_checkpoint_path(cfg.checkpoint) if cfg.checkpoint is None: quit() cfg_dict = omegaconf_to_dict(cfg) print_dict(cfg_dict) # sets seed. if seed is -1 will pick a random one from omni.isaac.core.utils.torch.maths import set_seed cfg.seed = set_seed(cfg.seed, torch_deterministic=cfg.torch_deterministic) cfg_dict['seed'] = cfg.seed task = initialize_demo(cfg_dict, env) if cfg.wandb_activate: # Make sure to install WandB if you actually use this. import wandb run_name = f"{cfg.wandb_name}_{time_str}" wandb.init( project=cfg.wandb_project, group=cfg.wandb_group, entity=cfg.wandb_entity, config=cfg_dict, sync_tensorboard=True, id=run_name, resume="allow", monitor_gym=True, ) rlg_trainer = RLGDemo(cfg, cfg_dict) rlg_trainer.launch_rlg_hydra(env) rlg_trainer.run() env.close() if cfg.wandb_activate: wandb.finish() if __name__ == '__main__': parse_hydra_configs()
3,647
Python
35.118812
80
0.713737
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/scripts/rlgames_train.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. 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. # # 3. Neither the name of the copyright holder 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 WARRANTIES, 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, INDIRECT, 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. from swervesim.utils.hydra_cfg.hydra_utils import * from swervesim.utils.hydra_cfg.reformat import omegaconf_to_dict, print_dict from swervesim.utils.rlgames.rlgames_utils import RLGPUAlgoObserver, RLGPUEnv from swervesim.utils.task_util import initialize_task from swervesim.utils.config_utils.path_utils import retrieve_checkpoint_path from swervesim.envs.vec_env_rlgames import VecEnvRLGames import hydra from omegaconf import DictConfig from rl_games.common import env_configurations, vecenv from rl_games.torch_runner import Runner import datetime import os import torch class RLGTrainer(): def __init__(self, cfg, cfg_dict): self.cfg = cfg self.cfg_dict = cfg_dict def launch_rlg_hydra(self, env): # `create_rlgpu_env` is environment construction function which is passed to RL Games and called internally. # We use the helper function here to specify the environment config. self.cfg_dict["task"]["test"] = self.cfg.test # register the rl-games adapter to use inside the runner vecenv.register('RLGPU', lambda config_name, num_actors, **kwargs: RLGPUEnv(config_name, num_actors, **kwargs)) env_configurations.register('rlgpu', { 'vecenv_type': 'RLGPU', 'env_creator': lambda **kwargs: env }) self.rlg_config_dict = omegaconf_to_dict(self.cfg.train) def run(self): # create runner and set the settings runner = Runner(RLGPUAlgoObserver()) runner.load(self.rlg_config_dict) runner.reset() # dump config dict experiment_dir = os.path.join('runs', self.cfg.train.params.config.name) os.makedirs(experiment_dir, exist_ok=True) with open(os.path.join(experiment_dir, 'config.yaml'), 'w') as f: f.write(OmegaConf.to_yaml(self.cfg)) runner.run({ 'train': not self.cfg.test, 'play': self.cfg.test, 'checkpoint': self.cfg.checkpoint, 'sigma': None }) @hydra.main(config_name="config", config_path="../cfg") def parse_hydra_configs(cfg: DictConfig): time_str = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") headless = cfg.headless env = VecEnvRLGames(headless=headless, sim_device=cfg.device_id) # ensure checkpoints can be specified as relative paths if cfg.checkpoint: cfg.checkpoint = retrieve_checkpoint_path(cfg.checkpoint) if cfg.checkpoint is None: quit() cfg_dict = omegaconf_to_dict(cfg) print_dict(cfg_dict) # sets seed. if seed is -1 will pick a random one from omni.isaac.core.utils.torch.maths import set_seed cfg.seed = set_seed(cfg.seed, torch_deterministic=cfg.torch_deterministic) cfg_dict['seed'] = cfg.seed task = initialize_task(cfg_dict, env) if cfg.wandb_activate: # Make sure to install WandB if you actually use this. import wandb run_name = f"{cfg.wandb_name}_{time_str}" wandb.init( project=cfg.wandb_project, group=cfg.wandb_group, entity=cfg.wandb_entity, config=cfg_dict, sync_tensorboard=True, id=run_name, resume="allow", monitor_gym=True, ) rlg_trainer = RLGTrainer(cfg, cfg_dict) rlg_trainer.launch_rlg_hydra(env) rlg_trainer.run() env.close() if cfg.wandb_activate: wandb.finish() if __name__ == '__main__': parse_hydra_configs()
5,082
Python
35.307143
116
0.685557
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/scripts/random_policy.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. 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. # # 3. Neither the name of the copyright holder 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 WARRANTIES, 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, INDIRECT, 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. import numpy as np import torch import hydra from omegaconf import DictConfig from swervesim.utils.hydra_cfg.hydra_utils import * from swervesim.utils.hydra_cfg.reformat import omegaconf_to_dict, print_dict from swervesim.utils.task_util import initialize_task from swervesim.envs.vec_env_rlgames import VecEnvRLGames @hydra.main(config_name="config", config_path="../cfg") def parse_hydra_configs(cfg: DictConfig): cfg_dict = omegaconf_to_dict(cfg) print_dict(cfg_dict) headless = cfg.headless render = not headless env = VecEnvRLGames(headless=headless, sim_device=cfg.device_id) # sets seed. if seed is -1 will pick a random one from omni.isaac.core.utils.torch.maths import set_seed cfg.seed = set_seed(cfg.seed, torch_deterministic=cfg.torch_deterministic) cfg_dict['seed'] = cfg.seed task = initialize_task(cfg_dict, env) while env._simulation_app.is_running(): if env._world.is_playing(): if env._world.current_time_step_index == 0: env._world.reset(soft=True) actions = torch.tensor(np.array([env.action_space.sample() for _ in range(env.num_envs)]), device=task.rl_device) env._task.pre_physics_step(actions) env._world.step(render=render) env.sim_frame_count += 1 env._task.post_physics_step() else: env._world.step(render=render) env._simulation_app.close() if __name__ == '__main__': parse_hydra_configs()
3,055
Python
40.863013
125
0.728642
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/scripts/rlgames_train_mt.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. 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. # # 3. Neither the name of the copyright holder 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 WARRANTIES, 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, INDIRECT, 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. from swervesim.utils.hydra_cfg.hydra_utils import * from swervesim.utils.hydra_cfg.reformat import omegaconf_to_dict, print_dict from swervesim.utils.rlgames.rlgames_utils import RLGPUAlgoObserver, RLGPUEnv from swervesim.utils.task_util import initialize_task from swervesim.utils.config_utils.path_utils import retrieve_checkpoint_path from swervesim.envs.vec_env_rlgames_mt import VecEnvRLGamesMT import hydra from omegaconf import DictConfig from rl_games.common import env_configurations, vecenv from rl_games.torch_runner import Runner import copy import datetime import os import threading import queue from omni.isaac.gym.vec_env.vec_env_mt import TrainerMT class RLGTrainer(): def __init__(self, cfg, cfg_dict): self.cfg = cfg self.cfg_dict = cfg_dict def launch_rlg_hydra(self, env): # `create_rlgpu_env` is environment construction function which is passed to RL Games and called internally. # We use the helper function here to specify the environment config. self.cfg_dict["task"]["test"] = self.cfg.test # register the rl-games adapter to use inside the runner vecenv.register('RLGPU', lambda config_name, num_actors, **kwargs: RLGPUEnv(config_name, num_actors, **kwargs)) env_configurations.register('rlgpu', { 'vecenv_type': 'RLGPU', 'env_creator': lambda **kwargs: env }) self.rlg_config_dict = omegaconf_to_dict(self.cfg.train) def run(self): # create runner and set the settings runner = Runner(RLGPUAlgoObserver()) runner.load(copy.deepcopy(self.rlg_config_dict)) runner.reset() # dump config dict experiment_dir = os.path.join('runs', self.cfg.train.params.config.name) os.makedirs(experiment_dir, exist_ok=True) with open(os.path.join(experiment_dir, 'config.yaml'), 'w') as f: f.write(OmegaConf.to_yaml(self.cfg)) time_str = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") if self.cfg.wandb_activate: # Make sure to install WandB if you actually use this. import wandb run_name = f"{self.cfg.wandb_name}_{time_str}" wandb.init( project=self.cfg.wandb_project, group=self.cfg.wandb_group, entity=self.cfg.wandb_entity, config=self.cfg_dict, sync_tensorboard=True, id=run_name, resume="allow", monitor_gym=True, ) runner.run({ 'train': not self.cfg.test, 'play': self.cfg.test, 'checkpoint': self.cfg.checkpoint, 'sigma': None }) if self.cfg.wandb_activate: wandb.finish() class Trainer(TrainerMT): def __init__(self, trainer, env): self.ppo_thread = None self.action_queue = None self.data_queue = None self.trainer = trainer self.is_running = False self.env = env self.create_task() self.run() def create_task(self): self.trainer.launch_rlg_hydra(self.env) task = initialize_task(self.trainer.cfg_dict, self.env, init_sim=False) self.task = task def run(self): self.is_running = True self.action_queue = queue.Queue(1) self.data_queue = queue.Queue(1) if "mt_timeout" in self.trainer.cfg_dict: self.env.initialize(self.action_queue, self.data_queue, self.trainer.cfg_dict["mt_timeout"]) else: self.env.initialize(self.action_queue, self.data_queue) self.ppo_thread = PPOTrainer(self.env, self.task, self.trainer) self.ppo_thread.daemon = True self.ppo_thread.start() def stop(self): self.env.stop = True self.env.clear_queues() if self.action_queue: self.action_queue.join() if self.data_queue: self.data_queue.join() if self.ppo_thread: self.ppo_thread.join() self.action_queue = None self.data_queue = None self.ppo_thread = None self.is_running = False class PPOTrainer(threading.Thread): def __init__(self, env, task, trainer): super().__init__() self.env = env self.task = task self.trainer = trainer def run(self): from omni.isaac.gym.vec_env import TaskStopException print("starting ppo...") try: self.trainer.run() # trainer finished - send stop signal to main thread self.env.send_actions(None) self.env.stop = True except TaskStopException: print("Task Stopped!") @hydra.main(config_name="config", config_path="../cfg") def parse_hydra_configs(cfg: DictConfig): headless = cfg.headless env = VecEnvRLGamesMT(headless=headless, sim_device=cfg.device_id) # ensure checkpoints can be specified as relative paths if cfg.checkpoint: cfg.checkpoint = retrieve_checkpoint_path(cfg.checkpoint) if cfg.checkpoint is None: quit() cfg_dict = omegaconf_to_dict(cfg) print_dict(cfg_dict) # sets seed. if seed is -1 will pick a random one from omni.isaac.core.utils.torch.maths import set_seed cfg.seed = set_seed(cfg.seed, torch_deterministic=cfg.torch_deterministic) cfg_dict['seed'] = cfg.seed rlg_trainer = RLGTrainer(cfg, cfg_dict) trainer = Trainer(rlg_trainer, env) trainer.env.run(trainer) if __name__ == '__main__': parse_hydra_configs()
7,192
Python
33.416268
116
0.652392
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/utils/demo_util.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. 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. # # 3. Neither the name of the copyright holder 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 WARRANTIES, 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, INDIRECT, 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. def initialize_demo(config, env, init_sim=True): from swervesim.demos.anymal_terrain import AnymalTerrainDemo # Mappings from strings to environments task_map = { "AnymalTerrain": AnymalTerrainDemo, } from swervesim.utils.config_utils.sim_config import SimConfig sim_config = SimConfig(config) cfg = sim_config.config task = task_map[cfg["task_name"]]( name=cfg["task_name"], sim_config=sim_config, env=env ) env.set_task(task=task, sim_params=sim_config.get_physics_params(), backend="torch", init_sim=init_sim) return task
2,153
Python
43.874999
107
0.75569
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/utils/task_util.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. 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. # # 3. Neither the name of the copyright holder 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 WARRANTIES, 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, INDIRECT, 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. def initialize_task(config, env, init_sim=True): from swervesim.tasks.swerve import Swerve_Task from swervesim.tasks.swerve_with_kinematics import Swerve_Kinematics_Task from swervesim.tasks.swerve_field import Swerve_Field_Task from swervesim.tasks.swerve_multi_action_auton import Swerve_Multi_Action_Task from swervesim.tasks.swerve_charge_station import Swerve_Charge_Station_Task # Mappings from strings to environments task_map = { "Swerve": Swerve_Task, "SwerveK": Swerve_Kinematics_Task, "SwerveF": Swerve_Field_Task, "SwerveMAA": Swerve_Multi_Action_Task, "SwerveCS": Swerve_Charge_Station_Task, } from .config_utils.sim_config import SimConfig sim_config = SimConfig(config) cfg = sim_config.config task = task_map[cfg["task_name"]]( name=cfg["task_name"], sim_config=sim_config, env=env ) env.set_task(task=task, sim_params=sim_config.get_physics_params(), backend="torch", init_sim=init_sim) return task
2,593
Python
44.508771
107
0.748939
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/utils/domain_randomization/randomize.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. 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. # # 3. Neither the name of the copyright holder 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 WARRANTIES, 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, INDIRECT, 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. import copy import omni import omni.replicator.core as rep import omni.replicator.isaac as dr import numpy as np import torch from omni.isaac.core.prims import RigidPrimView class Randomizer(): def __init__(self, sim_config): self._cfg = sim_config.task_config self._config = sim_config.config self.randomize = False dr_config = self._cfg.get("domain_randomization", None) self.distributions = dict() self.active_domain_randomizations = dict() self._observations_dr_params = None self._actions_dr_params = None if dr_config is not None: randomize = dr_config.get("randomize", False) randomization_params = dr_config.get("randomization_params", None) if randomize and randomization_params is not None: self.randomize = True self.min_frequency = dr_config.get("min_frequency", 1) def apply_on_startup_domain_randomization(self, task): if self.randomize: torch.manual_seed(self._config["seed"]) randomization_params = self._cfg["domain_randomization"]["randomization_params"] for opt in randomization_params.keys(): if opt == "rigid_prim_views": if randomization_params["rigid_prim_views"] is not None: for view_name in randomization_params["rigid_prim_views"].keys(): if randomization_params["rigid_prim_views"][view_name] is not None: for attribute, params in randomization_params["rigid_prim_views"][view_name].items(): params = randomization_params["rigid_prim_views"][view_name][attribute] if attribute in ["scale", "mass", "density"] and params is not None: if "on_startup" in params.keys(): if not set(('operation','distribution', 'distribution_parameters')).issubset(params["on_startup"]): raise ValueError(f"Please ensure the following randomization parameters for {view_name} {attribute} " + \ "on_startup are provided: operation, distribution, distribution_parameters.") view = task._env._world.scene._scene_registry.rigid_prim_views[view_name] if attribute == "scale": self.randomize_scale_on_startup( view=view, distribution=params["on_startup"]["distribution"], distribution_parameters=params["on_startup"]["distribution_parameters"], operation=params["on_startup"]["operation"], sync_dim_noise=True, ) elif attribute == "mass": self.randomize_mass_on_startup( view=view, distribution=params["on_startup"]["distribution"], distribution_parameters=params["on_startup"]["distribution_parameters"], operation=params["on_startup"]["operation"], ) elif attribute == "density": self.randomize_density_on_startup( view=view, distribution=params["on_startup"]["distribution"], distribution_parameters=params["on_startup"]["distribution_parameters"], operation=params["on_startup"]["operation"], ) if opt == "articulation_views": if randomization_params["articulation_views"] is not None: for view_name in randomization_params["articulation_views"].keys(): if randomization_params["articulation_views"][view_name] is not None: for attribute, params in randomization_params["articulation_views"][view_name].items(): params = randomization_params["articulation_views"][view_name][attribute] if attribute in ["scale"] and params is not None: if "on_startup" in params.keys(): if not set(('operation','distribution', 'distribution_parameters')).issubset(params["on_startup"]): raise ValueError(f"Please ensure the following randomization parameters for {view_name} {attribute} " + \ "on_startup are provided: operation, distribution, distribution_parameters.") view = task._env._world.scene._scene_registry.articulated_views[view_name] if attribute == "scale": self.randomize_scale_on_startup( view=view, distribution=params["on_startup"]["distribution"], distribution_parameters=params["on_startup"]["distribution_parameters"], operation=params["on_startup"]["operation"], sync_dim_noise=True ) else: dr_config = self._cfg.get("domain_randomization", None) if dr_config is None: raise ValueError("No domain randomization parameters are specified in the task yaml config file") randomize = dr_config.get("randomize", False) randomization_params = dr_config.get("randomization_params", None) if randomize == False or randomization_params is None: print("On Startup Domain randomization will not be applied.") def set_up_domain_randomization(self, task): if self.randomize: randomization_params = self._cfg["domain_randomization"]["randomization_params"] rep.set_global_seed(self._config["seed"]) with dr.trigger.on_rl_frame(num_envs=self._cfg["env"]["numEnvs"]): for opt in randomization_params.keys(): if opt == "observations": self._set_up_observations_randomization(task) elif opt == "actions": self._set_up_actions_randomization(task) elif opt == "simulation": if randomization_params["simulation"] is not None: self.distributions["simulation"] = dict() dr.physics_view.register_simulation_context(task._env._world) for attribute, params in randomization_params["simulation"].items(): self._set_up_simulation_randomization(attribute, params) elif opt == "rigid_prim_views": if randomization_params["rigid_prim_views"] is not None: self.distributions["rigid_prim_views"] = dict() for view_name in randomization_params["rigid_prim_views"].keys(): if randomization_params["rigid_prim_views"][view_name] is not None: self.distributions["rigid_prim_views"][view_name] = dict() dr.physics_view.register_rigid_prim_view( rigid_prim_view=task._env._world.scene._scene_registry.rigid_prim_views[view_name], ) for attribute, params in randomization_params["rigid_prim_views"][view_name].items(): if attribute not in ["scale", "density"]: self._set_up_rigid_prim_view_randomization(view_name, attribute, params) elif opt == "articulation_views": if randomization_params["articulation_views"] is not None: self.distributions["articulation_views"] = dict() for view_name in randomization_params["articulation_views"].keys(): if randomization_params["articulation_views"][view_name] is not None: self.distributions["articulation_views"][view_name] = dict() dr.physics_view.register_articulation_view( articulation_view=task._env._world.scene._scene_registry.articulated_views[view_name], ) for attribute, params in randomization_params["articulation_views"][view_name].items(): if attribute not in ["scale"]: self._set_up_articulation_view_randomization(view_name, attribute, params) rep.orchestrator.run() else: dr_config = self._cfg.get("domain_randomization", None) if dr_config is None: raise ValueError("No domain randomization parameters are specified in the task yaml config file") randomize = dr_config.get("randomize", False) randomization_params = dr_config.get("randomization_params", None) if randomize == False or randomization_params is None: print("Domain randomization will not be applied.") def _set_up_observations_randomization(self, task): task.randomize_observations = True self._observations_dr_params = self._cfg["domain_randomization"]["randomization_params"]["observations"] if self._observations_dr_params is None: raise ValueError(f"Observations randomization parameters are not provided.") if "on_reset" in self._observations_dr_params.keys(): if not set(('operation','distribution', 'distribution_parameters')).issubset(self._observations_dr_params["on_reset"].keys()): raise ValueError(f"Please ensure the following observations on_reset randomization parameters are provided: " + \ "operation, distribution, distribution_parameters.") self.active_domain_randomizations[("observations", "on_reset")] = np.array(self._observations_dr_params["on_reset"]["distribution_parameters"]) if "on_interval" in self._observations_dr_params.keys(): if not set(('frequency_interval', 'operation','distribution', 'distribution_parameters')).issubset(self._observations_dr_params["on_interval"].keys()): raise ValueError(f"Please ensure the following observations on_interval randomization parameters are provided: " + \ "frequency_interval, operation, distribution, distribution_parameters.") self.active_domain_randomizations[("observations", "on_interval")] = np.array(self._observations_dr_params["on_interval"]["distribution_parameters"]) self._observations_counter_buffer = torch.zeros((self._cfg["env"]["numEnvs"]), dtype=torch.int, device=self._config["rl_device"]) self._observations_correlated_noise = torch.zeros((self._cfg["env"]["numEnvs"], task.num_observations), device=self._config["rl_device"]) def _set_up_actions_randomization(self, task): task.randomize_actions = True self._actions_dr_params = self._cfg["domain_randomization"]["randomization_params"]["actions"] if self._actions_dr_params is None: raise ValueError(f"Actions randomization parameters are not provided.") if "on_reset" in self._actions_dr_params.keys(): if not set(('operation','distribution', 'distribution_parameters')).issubset(self._actions_dr_params["on_reset"].keys()): raise ValueError(f"Please ensure the following actions on_reset randomization parameters are provided: " + \ "operation, distribution, distribution_parameters.") self.active_domain_randomizations[("actions", "on_reset")] = np.array(self._actions_dr_params["on_reset"]["distribution_parameters"]) if "on_interval" in self._actions_dr_params.keys(): if not set(('frequency_interval', 'operation','distribution', 'distribution_parameters')).issubset(self._actions_dr_params["on_interval"].keys()): raise ValueError(f"Please ensure the following actions on_interval randomization parameters are provided: " + \ "frequency_interval, operation, distribution, distribution_parameters.") self.active_domain_randomizations[("actions", "on_interval")] = np.array(self._actions_dr_params["on_interval"]["distribution_parameters"]) self._actions_counter_buffer = torch.zeros((self._cfg["env"]["numEnvs"]), dtype=torch.int, device=self._config["rl_device"]) self._actions_correlated_noise = torch.zeros((self._cfg["env"]["numEnvs"], task.num_actions), device=self._config["rl_device"]) def apply_observations_randomization(self, observations, reset_buf): env_ids = reset_buf.nonzero(as_tuple=False).squeeze(-1) self._observations_counter_buffer[env_ids] = 0 self._observations_counter_buffer += 1 if "on_reset" in self._observations_dr_params.keys(): observations[:] = self._apply_correlated_noise( buffer_type="observations", buffer=observations, reset_ids=env_ids, operation=self._observations_dr_params["on_reset"]["operation"], distribution=self._observations_dr_params["on_reset"]["distribution"], distribution_parameters=self._observations_dr_params["on_reset"]["distribution_parameters"], ) if "on_interval" in self._observations_dr_params.keys(): randomize_ids = (self._observations_counter_buffer >= self._observations_dr_params["on_interval"]["frequency_interval"]).nonzero(as_tuple=False).squeeze(-1) self._observations_counter_buffer[randomize_ids] = 0 observations[:] = self._apply_uncorrelated_noise( buffer=observations, randomize_ids=randomize_ids, operation=self._observations_dr_params["on_interval"]["operation"], distribution=self._observations_dr_params["on_interval"]["distribution"], distribution_parameters=self._observations_dr_params["on_interval"]["distribution_parameters"], ) return observations def apply_actions_randomization(self, actions, reset_buf): env_ids = reset_buf.nonzero(as_tuple=False).squeeze(-1) self._actions_counter_buffer[env_ids] = 0 self._actions_counter_buffer += 1 if "on_reset" in self._actions_dr_params.keys(): actions[:] = self._apply_correlated_noise( buffer_type="actions", buffer=actions, reset_ids=env_ids, operation=self._actions_dr_params["on_reset"]["operation"], distribution=self._actions_dr_params["on_reset"]["distribution"], distribution_parameters=self._actions_dr_params["on_reset"]["distribution_parameters"], ) if "on_interval" in self._actions_dr_params.keys(): randomize_ids = (self._actions_counter_buffer >= self._actions_dr_params["on_interval"]["frequency_interval"]).nonzero(as_tuple=False).squeeze(-1) self._actions_counter_buffer[randomize_ids] = 0 actions[:] = self._apply_uncorrelated_noise( buffer=actions, randomize_ids=randomize_ids, operation=self._actions_dr_params["on_interval"]["operation"], distribution=self._actions_dr_params["on_interval"]["distribution"], distribution_parameters=self._actions_dr_params["on_interval"]["distribution_parameters"], ) return actions def _apply_uncorrelated_noise(self, buffer, randomize_ids, operation, distribution, distribution_parameters): if distribution == "gaussian" or distribution == "normal": noise = torch.normal(mean=distribution_parameters[0], std=distribution_parameters[1], size=(len(randomize_ids), buffer.shape[1]), device=self._config["rl_device"]) elif distribution == "uniform": noise = (distribution_parameters[1] - distribution_parameters[0]) * torch.rand((len(randomize_ids), buffer.shape[1]), device=self._config["rl_device"]) + distribution_parameters[0] elif distribution == "loguniform" or distribution == "log_uniform": noise = torch.exp((np.log(distribution_parameters[1]) - np.log(distribution_parameters[0])) * torch.rand((len(randomize_ids), buffer.shape[1]), device=self._config["rl_device"]) + np.log(distribution_parameters[0])) else: print(f"The specified {distribution} distribution is not supported.") if operation == "additive": buffer[randomize_ids] += noise elif operation == "scaling": buffer[randomize_ids] *= noise else: print(f"The specified {operation} operation type is not supported.") return buffer def _apply_correlated_noise(self, buffer_type, buffer, reset_ids, operation, distribution, distribution_parameters): if buffer_type == "observations": correlated_noise_buffer = self._observations_correlated_noise elif buffer_type == "actions": correlated_noise_buffer = self._actions_correlated_noise if len(reset_ids) > 0: if distribution == "gaussian" or distribution == "normal": correlated_noise_buffer[reset_ids] = torch.normal(mean=distribution_parameters[0], std=distribution_parameters[1], size=(len(reset_ids), buffer.shape[1]), device=self._config["rl_device"]) elif distribution == "uniform": correlated_noise_buffer[reset_ids] = (distribution_parameters[1] - distribution_parameters[0]) * torch.rand((len(reset_ids), buffer.shape[1]), device=self._config["rl_device"]) + distribution_parameters[0] elif distribution == "loguniform" or distribution == "log_uniform": correlated_noise_buffer[reset_ids] = torch.exp((np.log(distribution_parameters[1]) - np.log(distribution_parameters[0])) * torch.rand((len(reset_ids), buffer.shape[1]), device=self._config["rl_device"]) + np.log(distribution_parameters[0])) else: print(f"The specified {distribution} distribution is not supported.") if operation == "additive": buffer += correlated_noise_buffer elif operation == "scaling": buffer *= correlated_noise_buffer else: print(f"The specified {operation} operation type is not supported.") return buffer def _set_up_simulation_randomization(self, attribute, params): if params is None: raise ValueError(f"Randomization parameters for simulation {attribute} is not provided.") if attribute in dr.SIMULATION_CONTEXT_ATTRIBUTES: self.distributions["simulation"][attribute] = dict() if "on_reset" in params.keys(): if not set(('operation','distribution', 'distribution_parameters')).issubset(params["on_reset"]): raise ValueError(f"Please ensure the following randomization parameters for simulation {attribute} on_reset are provided: " + \ "operation, distribution, distribution_parameters.") self.active_domain_randomizations[("simulation", attribute, "on_reset")] = np.array(params["on_reset"]["distribution_parameters"]) kwargs = {"operation": params["on_reset"]["operation"]} self.distributions["simulation"][attribute]["on_reset"] = self._generate_distribution( dimension=dr.physics_view._simulation_context_initial_values[attribute].shape[0], view_name="simulation", attribute=attribute, params=params["on_reset"], ) kwargs[attribute] = self.distributions["simulation"][attribute]["on_reset"] with dr.gate.on_env_reset(): dr.physics_view.randomize_simulation_context(**kwargs) if "on_interval" in params.keys(): if not set(('frequency_interval', 'operation','distribution', 'distribution_parameters')).issubset(params["on_interval"]): raise ValueError(f"Please ensure the following randomization parameters for simulation {attribute} on_interval are provided: " + \ "frequency_interval, operation, distribution, distribution_parameters.") self.active_domain_randomizations[("simulation", attribute, "on_interval")] = np.array(params["on_interval"]["distribution_parameters"]) kwargs = {"operation": params["on_interval"]["operation"]} self.distributions["simulation"][attribute]["on_interval"] = self._generate_distribution( dimension=dr.physics_view._simulation_context_initial_values[attribute].shape[0], view_name="simulation", attribute=attribute, params=params["on_interval"], ) kwargs[attribute] = self.distributions["simulation"][attribute]["on_interval"] with dr.gate.on_interval(interval=params["on_interval"]["frequency_interval"]): dr.physics_view.randomize_simulation_context(**kwargs) def _set_up_rigid_prim_view_randomization(self, view_name, attribute, params): if params is None: raise ValueError(f"Randomization parameters for rigid prim view {view_name} {attribute} is not provided.") if attribute in dr.RIGID_PRIM_ATTRIBUTES: self.distributions["rigid_prim_views"][view_name][attribute] = dict() if "on_reset" in params.keys(): if not set(('operation','distribution', 'distribution_parameters')).issubset(params["on_reset"]): raise ValueError(f"Please ensure the following randomization parameters for {view_name} {attribute} on_reset are provided: " + \ "operation, distribution, distribution_parameters.") self.active_domain_randomizations[("rigid_prim_views", view_name, attribute, "on_reset")] = np.array(params["on_reset"]["distribution_parameters"]) kwargs = {"view_name": view_name, "operation": params["on_reset"]["operation"]} if attribute == "material_properties" and "num_buckets" in params["on_reset"].keys(): kwargs["num_buckets"] = params["on_reset"]["num_buckets"] self.distributions["rigid_prim_views"][view_name][attribute]["on_reset"] = self._generate_distribution( dimension=dr.physics_view._rigid_prim_views_initial_values[view_name][attribute].shape[1], view_name=view_name, attribute=attribute, params=params["on_reset"], ) kwargs[attribute] = self.distributions["rigid_prim_views"][view_name][attribute]["on_reset"] with dr.gate.on_env_reset(): dr.physics_view.randomize_rigid_prim_view(**kwargs) if "on_interval" in params.keys(): if not set(('frequency_interval', 'operation','distribution', 'distribution_parameters')).issubset(params["on_interval"]): raise ValueError(f"Please ensure the following randomization parameters for {view_name} {attribute} on_interval are provided: " + \ "frequency_interval, operation, distribution, distribution_parameters.") self.active_domain_randomizations[("rigid_prim_views", view_name, attribute, "on_interval")] = np.array(params["on_interval"]["distribution_parameters"]) kwargs = {"view_name": view_name, "operation": params["on_interval"]["operation"]} if attribute == "material_properties" and "num_buckets" in params["on_interval"].keys(): kwargs["num_buckets"] = params["on_interval"]["num_buckets"] self.distributions["rigid_prim_views"][view_name][attribute]["on_interval"] = self._generate_distribution( dimension=dr.physics_view._rigid_prim_views_initial_values[view_name][attribute].shape[1], view_name=view_name, attribute=attribute, params=params["on_interval"], ) kwargs[attribute] = self.distributions["rigid_prim_views"][view_name][attribute]["on_interval"] with dr.gate.on_interval(interval=params["on_interval"]["frequency_interval"]): dr.physics_view.randomize_rigid_prim_view(**kwargs) else: raise ValueError(f"The attribute {attribute} for {view_name} is invalid for domain randomization.") def _set_up_articulation_view_randomization(self, view_name, attribute, params): if params is None: raise ValueError(f"Randomization parameters for articulation view {view_name} {attribute} is not provided.") if attribute in dr.ARTICULATION_ATTRIBUTES: self.distributions["articulation_views"][view_name][attribute] = dict() if "on_reset" in params.keys(): if not set(('operation','distribution', 'distribution_parameters')).issubset(params["on_reset"]): raise ValueError(f"Please ensure the following randomization parameters for {view_name} {attribute} on_reset are provided: " + \ "operation, distribution, distribution_parameters.") self.active_domain_randomizations[("articulation_views", view_name, attribute, "on_reset")] = np.array(params["on_reset"]["distribution_parameters"]) kwargs = {"view_name": view_name, "operation": params["on_reset"]["operation"]} if attribute == "material_properties" and "num_buckets" in params["on_reset"].keys(): kwargs["num_buckets"] = params["on_reset"]["num_buckets"] self.distributions["articulation_views"][view_name][attribute]["on_reset"] = self._generate_distribution( dimension=dr.physics_view._articulation_views_initial_values[view_name][attribute].shape[1], view_name=view_name, attribute=attribute, params=params["on_reset"], ) kwargs[attribute] = self.distributions["articulation_views"][view_name][attribute]["on_reset"] with dr.gate.on_env_reset(): dr.physics_view.randomize_articulation_view(**kwargs) if "on_interval" in params.keys(): if not set(('frequency_interval', 'operation','distribution', 'distribution_parameters')).issubset(params["on_interval"]): raise ValueError(f"Please ensure the following randomization parameters for {view_name} {attribute} on_interval are provided: " + \ "frequency_interval, operation, distribution, distribution_parameters.") self.active_domain_randomizations[("articulation_views", view_name, attribute, "on_interval")] = np.array(params["on_interval"]["distribution_parameters"]) kwargs = {"view_name": view_name, "operation": params["on_interval"]["operation"]} if attribute == "material_properties" and "num_buckets" in params["on_interval"].keys(): kwargs["num_buckets"] = params["on_interval"]["num_buckets"] self.distributions["articulation_views"][view_name][attribute]["on_interval"] = self._generate_distribution( dimension=dr.physics_view._articulation_views_initial_values[view_name][attribute].shape[1], view_name=view_name, attribute=attribute, params=params["on_interval"], ) kwargs[attribute] = self.distributions["articulation_views"][view_name][attribute]["on_interval"] with dr.gate.on_interval(interval=params["on_interval"]["frequency_interval"]): dr.physics_view.randomize_articulation_view(**kwargs) else: raise ValueError(f"The attribute {attribute} for {view_name} is invalid for domain randomization.") def _generate_distribution(self, view_name, attribute, dimension, params): dist_params = self._sanitize_distribution_parameters(attribute, dimension, params["distribution_parameters"]) if params["distribution"] == "uniform": return rep.distribution.uniform(tuple(dist_params[0]), tuple(dist_params[1])) elif params["distribution"] == "gaussian" or params["distribution"] == "normal": return rep.distribution.normal(tuple(dist_params[0]), tuple(dist_params[1])) elif params["distribution"] == "loguniform" or params["distribution"] == "log_uniform": return rep.distribution.log_uniform(tuple(dist_params[0]), tuple(dist_params[1])) else: raise ValueError(f"The provided distribution for {view_name} {attribute} is not supported. " + "Options: uniform, gaussian/normal, loguniform/log_uniform" ) def _sanitize_distribution_parameters(self, attribute, dimension, params): distribution_parameters = np.array(params) if distribution_parameters.shape == (2,): # if the user does not provide a set of parameters for each dimension dist_params = [[distribution_parameters[0]]*dimension, [distribution_parameters[1]]*dimension] elif distribution_parameters.shape == (2, dimension): # if the user provides a set of parameters for each dimension in the format [[...], [...]] dist_params = distribution_parameters.tolist() elif attribute in ["material_properties", "body_inertias"] and distribution_parameters.shape == (2, 3): # if the user only provides the parameters for one body in the articulation, assume the same parameters for all other links dist_params = [[distribution_parameters[0]] * (dimension // 3), [distribution_parameters[1]] * (dimension // 3)] else: raise ValueError(f"The provided distribution_parameters for {view_name} {attribute} is invalid due to incorrect dimensions.") return dist_params def set_dr_distribution_parameters(self, distribution_parameters, *distribution_path): if distribution_path not in self.active_domain_randomizations.keys(): raise ValueError(f"Cannot find a valid domain randomization distribution using the path {distribution_path}.") if distribution_path[0] == "observations": if len(distribution_parameters) == 2: self._observations_dr_params[distribution_path[1]]["distribution_parameters"] = distribution_parameters else: raise ValueError(f"Please provide distribution_parameters for observations {distribution_path[1]} " + "in the form of [dist_param_1, dist_param_2]") elif distribution_path[0] == "actions": if len(distribution_parameters) == 2: self._actions_dr_params[distribution_path[1]]["distribution_parameters"] = distribution_parameters else: raise ValueError(f"Please provide distribution_parameters for actions {distribution_path[1]} " + "in the form of [dist_param_1, dist_param_2]") else: replicator_distribution = self.distributions[distribution_path[0]][distribution_path[1]][distribution_path[2]] if distribution_path[0] == "rigid_prim_views" or distribution_path[0] == "articulation_views": replicator_distribution = replicator_distribution[distribution_path[3]] if replicator_distribution.node.get_node_type().get_node_type() == "omni.replicator.core.OgnSampleUniform" \ or replicator_distribution.node.get_node_type().get_node_type() == "omni.replicator.core.OgnSampleLogUniform": dimension = len(dr.utils.get_distribution_params(replicator_distribution, ["lower"])[0]) dist_params = self._sanitize_distribution_parameters(distribution_path[-2], dimension, distribution_parameters) dr.utils.set_distribution_params(replicator_distribution, {"lower": dist_params[0], "upper": dist_params[1]}) elif replicator_distribution.node.get_node_type().get_node_type() == "omni.replicator.core.OgnSampleNormal": dimension = len(dr.utils.get_distribution_params(replicator_distribution, ["mean"])[0]) dist_params = self._sanitize_distribution_parameters(distribution_path[-2], dimension, distribution_parameters) dr.utils.set_distribution_params(replicator_distribution, {"mean": dist_params[0], "std": dist_params[1]}) def get_dr_distribution_parameters(self, *distribution_path): if distribution_path not in self.active_domain_randomizations.keys(): raise ValueError(f"Cannot find a valid domain randomization distribution using the path {distribution_path}.") if distribution_path[0] == "observations": return self._observations_dr_params[distribution_path[1]]["distribution_parameters"] elif distribution_path[0] == "actions": return self._actions_dr_params[distribution_path[1]]["distribution_parameters"] else: replicator_distribution = self.distributions[distribution_path[0]][distribution_path[1]][distribution_path[2]] if distribution_path[0] == "rigid_prim_views" or distribution_path[0] == "articulation_views": replicator_distribution = replicator_distribution[distribution_path[3]] if replicator_distribution.node.get_node_type().get_node_type() == "omni.replicator.core.OgnSampleUniform" \ or replicator_distribution.node.get_node_type().get_node_type() == "omni.replicator.core.OgnSampleLogUniform": return dr.utils.get_distribution_params(replicator_distribution, ["lower", "upper"]) elif replicator_distribution.node.get_node_type().get_node_type() == "omni.replicator.core.OgnSampleNormal": return dr.utils.get_distribution_params(replicator_distribution, ["mean", "std"]) def get_initial_dr_distribution_parameters(self, *distribution_path): if distribution_path not in self.active_domain_randomizations.keys(): raise ValueError(f"Cannot find a valid domain randomization distribution using the path {distribution_path}.") return self.active_domain_randomizations[distribution_path].copy() def _generate_noise(self, distribution, distribution_parameters, size, device): if distribution == "gaussian" or distribution == "normal": noise = torch.normal(mean=distribution_parameters[0], std=distribution_parameters[1], size=size, device=device) elif distribution == "uniform": noise = (distribution_parameters[1] - distribution_parameters[0]) * torch.rand(size, device=device) + distribution_parameters[0] elif distribution == "loguniform" or distribution == "log_uniform": noise = torch.exp((np.log(distribution_parameters[1]) - np.log(distribution_parameters[0])) * torch.rand(size, device=device) + np.log(distribution_parameters[0])) else: print(f"The specified {distribution} distribution is not supported.") return noise def randomize_scale_on_startup(self, view, distribution, distribution_parameters, operation, sync_dim_noise=True): scales = view.get_local_scales() if sync_dim_noise: dist_params = np.asarray(self._sanitize_distribution_parameters(attribute="scale", dimension=1, params=distribution_parameters)) noise = self._generate_noise(distribution, dist_params.squeeze(), (view.count,), view._device).repeat(3,1).T else: dist_params = np.asarray(self._sanitize_distribution_parameters(attribute="scale", dimension=3, params=distribution_parameters)) noise = torch.zeros((view.count, 3), device=view._device) for i in range(3): noise[:, i] = self._generate_noise(distribution, dist_params[:, i], (view.count,), view._device) if operation == "additive": scales += noise elif operation == "scaling": scales *= noise elif operation == "direct": scales = noise else: print(f"The specified {operation} operation type is not supported.") view.set_local_scales(scales=scales) def randomize_mass_on_startup(self, view, distribution, distribution_parameters, operation): if isinstance(view, omni.isaac.core.prims.RigidPrimView) or isinstance(view, RigidPrimView): masses = view.get_masses() dist_params = np.asarray(self._sanitize_distribution_parameters(attribute=f"{view.name} mass", dimension=1, params=distribution_parameters)) noise = self._generate_noise(distribution, dist_params.squeeze(), (view.count,), view._device) set_masses = view.set_masses if operation == "additive": masses += noise elif operation == "scaling": masses *= noise elif operation == "direct": masses = noise else: print(f"The specified {operation} operation type is not supported.") set_masses(masses) def randomize_density_on_startup(self, view, distribution, distribution_parameters, operation): if isinstance(view, omni.isaac.core.prims.RigidPrimView) or isinstance(view, RigidPrimView): densities = view.get_densities() dist_params = np.asarray(self._sanitize_distribution_parameters(attribute=f"{view.name} density", dimension=1, params=distribution_parameters)) noise = self._generate_noise(distribution, dist_params.squeeze(), (view.count,), view._device) set_densities = view.set_densities if operation == "additive": densities += noise elif operation == "scaling": densities *= noise elif operation == "direct": densities = noise else: print(f"The specified {operation} operation type is not supported.") set_densities(densities)
41,564
Python
70.787565
256
0.602877
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/utils/rlgames/rlgames_utils.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. 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. # # 3. Neither the name of the copyright holder 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 WARRANTIES, 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, INDIRECT, 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. from rl_games.common import env_configurations, vecenv from rl_games.common.algo_observer import AlgoObserver from rl_games.algos_torch import torch_ext import torch import numpy as np from typing import Callable class RLGPUAlgoObserver(AlgoObserver): """Allows us to log stats from the env along with the algorithm running stats. """ def __init__(self): pass def after_init(self, algo): self.algo = algo self.mean_scores = torch_ext.AverageMeter(1, self.algo.games_to_track).to(self.algo.ppo_device) self.ep_infos = [] self.direct_info = {} self.writer = self.algo.writer def process_infos(self, infos, done_indices): assert isinstance(infos, dict), "RLGPUAlgoObserver expects dict info" if isinstance(infos, dict): if 'episode' in infos: self.ep_infos.append(infos['episode']) if len(infos) > 0 and isinstance(infos, dict): # allow direct logging from env self.direct_info = {} for k, v in infos.items(): # only log scalars if isinstance(v, float) or isinstance(v, int) or (isinstance(v, torch.Tensor) and len(v.shape) == 0): self.direct_info[k] = v def after_clear_stats(self): self.mean_scores.clear() def after_print_stats(self, frame, epoch_num, total_time): if self.ep_infos: for key in self.ep_infos[0]: infotensor = torch.tensor([], device=self.algo.device) for ep_info in self.ep_infos: # handle scalar and zero dimensional tensor infos if not isinstance(ep_info[key], torch.Tensor): ep_info[key] = torch.Tensor([ep_info[key]]) if len(ep_info[key].shape) == 0: ep_info[key] = ep_info[key].unsqueeze(0) infotensor = torch.cat((infotensor, ep_info[key].to(self.algo.device))) value = torch.mean(infotensor) self.writer.add_scalar('Episode/' + key, value, epoch_num) self.ep_infos.clear() for k, v in self.direct_info.items(): self.writer.add_scalar(f'{k}/frame', v, frame) self.writer.add_scalar(f'{k}/iter', v, epoch_num) self.writer.add_scalar(f'{k}/time', v, total_time) if self.mean_scores.current_size > 0: mean_scores = self.mean_scores.get_mean() self.writer.add_scalar('scores/mean', mean_scores, frame) self.writer.add_scalar('scores/iter', mean_scores, epoch_num) self.writer.add_scalar('scores/time', mean_scores, total_time) class RLGPUEnv(vecenv.IVecEnv): def __init__(self, config_name, num_actors, **kwargs): self.env = env_configurations.configurations[config_name]['env_creator'](**kwargs) def step(self, action): return self.env.step(action) def reset(self): return self.env.reset() def get_number_of_agents(self): return self.env.get_number_of_agents() def get_env_info(self): info = {} info['action_space'] = self.env.action_space info['observation_space'] = self.env.observation_space if self.env.num_states > 0: info['state_space'] = self.env.state_space print(info['action_space'], info['observation_space'], info['state_space']) else: print(info['action_space'], info['observation_space']) return info
5,154
Python
42.319327
121
0.642608
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/utils/config_utils/sim_config.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. 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. # # 3. Neither the name of the copyright holder 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 WARRANTIES, 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, INDIRECT, 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. from swervesim.utils.config_utils.default_scene_params import * import copy import omni.usd import numpy as np import torch import carb class SimConfig(): def __init__(self, config: dict = None): if config is None: config = dict() self._config = config self._cfg = config.get("task", dict()) self._parse_config() if self._config["test"] == True: self._sim_params["enable_scene_query_support"] = True if self._config["headless"] == True and not self._sim_params["enable_cameras"]: self._sim_params["use_flatcache"] = False self._sim_params["enable_viewport"] = False if self._sim_params["disable_contact_processing"]: carb.settings.get_settings().set_bool("/physics/disableContactProcessing", True) def _parse_config(self): # general sim parameter self._sim_params = copy.deepcopy(default_sim_params) self._default_physics_material = copy.deepcopy(default_physics_material) sim_cfg = self._cfg.get("sim", None) if sim_cfg is not None: for opt in sim_cfg.keys(): if opt in self._sim_params: if opt == "default_physics_material": for material_opt in sim_cfg[opt]: self._default_physics_material[material_opt] = sim_cfg[opt][material_opt] else: self._sim_params[opt] = sim_cfg[opt] else: print("Sim params does not have attribute: ", opt) self._sim_params["default_physics_material"] = self._default_physics_material # physx parameters self._physx_params = copy.deepcopy(default_physx_params) if sim_cfg is not None and "physx" in sim_cfg: for opt in sim_cfg["physx"].keys(): if opt in self._physx_params: self._physx_params[opt] = sim_cfg["physx"][opt] else: print("Physx sim params does not have attribute: ", opt) self._sanitize_device() def _sanitize_device(self): if self._sim_params["use_gpu_pipeline"]: self._physx_params["use_gpu"] = True # device should be in sync with pipeline if self._sim_params["use_gpu_pipeline"]: self._config["sim_device"] = f"cuda:{self._config['device_id']}" else: self._config["sim_device"] = "cpu" # also write to physics params for setting sim device self._physx_params["sim_device"] = self._config["sim_device"] print("Pipeline: ", "GPU" if self._sim_params["use_gpu_pipeline"] else "CPU") print("Pipeline Device: ", self._config["sim_device"]) print("Sim Device: ", "GPU" if self._physx_params["use_gpu"] else "CPU") def parse_actor_config(self, actor_name): actor_params = copy.deepcopy(default_actor_options) if "sim" in self._cfg and actor_name in self._cfg["sim"]: actor_cfg = self._cfg["sim"][actor_name] for opt in actor_cfg.keys(): if actor_cfg[opt] != -1 and opt in actor_params: actor_params[opt] = actor_cfg[opt] elif opt not in actor_params: print("Actor params does not have attribute: ", opt) return actor_params def _get_actor_config_value(self, actor_name, attribute_name, attribute=None): actor_params = self.parse_actor_config(actor_name) if attribute is not None: if attribute_name not in actor_params: return attribute.Get() if actor_params[attribute_name] != -1: return actor_params[attribute_name] elif actor_params["override_usd_defaults"] and not attribute.IsAuthored(): return self._physx_params[attribute_name] else: if actor_params[attribute_name] != -1: return actor_params[attribute_name] @property def sim_params(self): return self._sim_params @property def config(self): return self._config @property def task_config(self): return self._cfg @property def physx_params(self): return self._physx_params def get_physics_params(self): return {**self.sim_params, **self.physx_params} def _get_physx_collision_api(self, prim): from pxr import UsdPhysics, PhysxSchema physx_collision_api = PhysxSchema.PhysxCollisionAPI(prim) if not physx_collision_api: physx_collision_api = PhysxSchema.PhysxCollisionAPI.Apply(prim) return physx_collision_api def _get_physx_rigid_body_api(self, prim): from pxr import UsdPhysics, PhysxSchema physx_rb_api = PhysxSchema.PhysxRigidBodyAPI(prim) if not physx_rb_api: physx_rb_api = PhysxSchema.PhysxRigidBodyAPI.Apply(prim) return physx_rb_api def _get_physx_articulation_api(self, prim): from pxr import UsdPhysics, PhysxSchema arti_api = PhysxSchema.PhysxArticulationAPI(prim) if not arti_api: arti_api = PhysxSchema.PhysxArticulationAPI.Apply(prim) return arti_api def set_contact_offset(self, name, prim, value=None): physx_collision_api = self._get_physx_collision_api(prim) contact_offset = physx_collision_api.GetContactOffsetAttr() # if not contact_offset: # contact_offset = physx_collision_api.CreateContactOffsetAttr() if value is None: value = self._get_actor_config_value(name, "contact_offset", contact_offset) if value != -1: contact_offset.Set(value) def set_rest_offset(self, name, prim, value=None): physx_collision_api = self._get_physx_collision_api(prim) rest_offset = physx_collision_api.GetRestOffsetAttr() # if not rest_offset: # rest_offset = physx_collision_api.CreateRestOffsetAttr() if value is None: value = self._get_actor_config_value(name, "rest_offset", rest_offset) if value != -1: rest_offset.Set(value) def set_position_iteration(self, name, prim, value=None): physx_rb_api = self._get_physx_rigid_body_api(prim) solver_position_iteration_count = physx_rb_api.GetSolverPositionIterationCountAttr() if value is None: value = self._get_actor_config_value(name, "solver_position_iteration_count", solver_position_iteration_count) if value != -1: solver_position_iteration_count.Set(value) def set_velocity_iteration(self, name, prim, value=None): physx_rb_api = self._get_physx_rigid_body_api(prim) solver_velocity_iteration_count = physx_rb_api.GetSolverVelocityIterationCountAttr() if value is None: value = self._get_actor_config_value(name, "solver_velocity_iteration_count", solver_position_iteration_count) if value != -1: solver_velocity_iteration_count.Set(value) def set_max_depenetration_velocity(self, name, prim, value=None): physx_rb_api = self._get_physx_rigid_body_api(prim) max_depenetration_velocity = physx_rb_api.GetMaxDepenetrationVelocityAttr() if value is None: value = self._get_actor_config_value(name, "max_depenetration_velocity", max_depenetration_velocity) if value != -1: max_depenetration_velocity.Set(value) def set_sleep_threshold(self, name, prim, value=None): physx_rb_api = self._get_physx_rigid_body_api(prim) sleep_threshold = physx_rb_api.GetSleepThresholdAttr() if value is None: value = self._get_actor_config_value(name, "sleep_threshold", sleep_threshold) if value != -1: sleep_threshold.Set(value) def set_stabilization_threshold(self, name, prim, value=None): physx_rb_api = self._get_physx_rigid_body_api(prim) stabilization_threshold = physx_rb_api.GetStabilizationThresholdAttr() if value is None: value = self._get_actor_config_value(name, "stabilization_threshold", stabilization_threshold) if value != -1: stabilization_threshold.Set(value) def set_gyroscopic_forces(self, name, prim, value=None): physx_rb_api = self._get_physx_rigid_body_api(prim) enable_gyroscopic_forces = physx_rb_api.GetEnableGyroscopicForcesAttr() if value is None: value = self._get_actor_config_value(name, "enable_gyroscopic_forces", enable_gyroscopic_forces) if value != -1: enable_gyroscopic_forces.Set(value) def set_density(self, name, prim, value=None): physx_rb_api = self._get_physx_rigid_body_api(prim) density = physx_rb_api.GetDensityAttr() if value is None: value = self._get_actor_config_value(name, "density", density) if value != -1: density.Set(value) # auto-compute mass self.set_mass(prim, 0.0) def set_mass(self, name, prim, value=None): physx_rb_api = self._get_physx_rigid_body_api(prim) mass = physx_rb_api.GetMassAttr() if value is None: value = self._get_actor_config_value(name, "mass", mass) if value != -1: mass.Set(value) def retain_acceleration(self, prim): # retain accelerations if running with more than one substep physx_rb_api = self._get_physx_rigid_body_api(prim) if self._sim_params["substeps"] > 1: physx_rb_api.GetRetainAccelerationsAttr().Set(True) def add_fixed_base(self, name, prim, cfg, value=None): # add fixed root joint for rigid body from pxr import UsdPhysics, PhysxSchema stage = omni.usd.get_context().get_stage() if value is None: value = self._get_actor_config_value(name, "fixed_base") if value: root_joint_path = f"{prim.GetPath()}_fixedBaseRootJoint" joint = UsdPhysics.Joint.Define(stage, root_joint_path) joint.CreateBody1Rel().SetTargets([prim.GetPath()]) self.apply_articulation_settings(name, joint.GetPrim(), cfg, force_articulation=True) def set_articulation_position_iteration(self, name, prim, value=None): arti_api = self._get_physx_articulation_api(prim) solver_position_iteration_count = arti_api.GetSolverPositionIterationCountAttr() if value is None: value = self._get_actor_config_value(name, "solver_position_iteration_count", solver_position_iteration_count) if value != -1: solver_position_iteration_count.Set(value) def set_articulation_velocity_iteration(self, name, prim, value=None): arti_api = self._get_physx_articulation_api(prim) solver_velocity_iteration_count = arti_api.GetSolverVelocityIterationCountAttr() if value is None: value = self._get_actor_config_value(name, "solver_velocity_iteration_count", solver_position_iteration_count) if value != -1: solver_velocity_iteration_count.Set(value) def set_articulation_sleep_threshold(self, name, prim, value=None): arti_api = self._get_physx_articulation_api(prim) sleep_threshold = arti_api.GetSleepThresholdAttr() if value is None: value = self._get_actor_config_value(name, "sleep_threshold", sleep_threshold) if value != -1: sleep_threshold.Set(value) def set_articulation_stabilization_threshold(self, name, prim, value=None): arti_api = self._get_physx_articulation_api(prim) stabilization_threshold = arti_api.GetStabilizationThresholdAttr() if value is None: value = self._get_actor_config_value(name, "stabilization_threshold", stabilization_threshold) if value != -1: stabilization_threshold.Set(value) def apply_rigid_body_settings(self, name, prim, cfg, is_articulation): from pxr import UsdPhysics, PhysxSchema stage = omni.usd.get_context().get_stage() rb_api = UsdPhysics.RigidBodyAPI.Get(stage, prim.GetPath()) physx_rb_api = PhysxSchema.PhysxRigidBodyAPI.Get(stage, prim.GetPath()) if not physx_rb_api: physx_rb_api = PhysxSchema.PhysxRigidBodyAPI.Apply(prim) # if it's a body in an articulation, it's handled at articulation root if not is_articulation: self.add_fixed_base(name, prim, cfg, cfg["fixed_base"]) self.set_position_iteration(name, prim, cfg["solver_position_iteration_count"]) self.set_velocity_iteration(name, prim, cfg["solver_velocity_iteration_count"]) self.set_max_depenetration_velocity(name, prim, cfg["max_depenetration_velocity"]) self.set_sleep_threshold(name, prim, cfg["sleep_threshold"]) self.set_stabilization_threshold(name, prim, cfg["stabilization_threshold"]) self.set_gyroscopic_forces(name, prim, cfg["enable_gyroscopic_forces"]) # density and mass mass_api = UsdPhysics.MassAPI.Get(stage, prim.GetPath()) if mass_api is None: mass_api = UsdPhysics.MassAPI.Apply(prim) mass_attr = mass_api.GetMassAttr() density_attr = mass_api.GetDensityAttr() if not mass_attr: mass_attr = mass_api.CreateMassAttr() if not density_attr: density_attr = mass_api.CreateDensityAttr() if cfg["density"] != -1: density_attr.Set(cfg["density"]) mass_attr.Set(0.0) # mass is to be computed elif cfg["override_usd_defaults"] and not density_attr.IsAuthored() and not mass_attr.IsAuthored(): density_attr.Set(self._physx_params["density"]) self.retain_acceleration(prim) def apply_rigid_shape_settings(self, name, prim, cfg): from pxr import UsdPhysics, PhysxSchema stage = omni.usd.get_context().get_stage() # collision APIs collision_api = UsdPhysics.CollisionAPI(prim) if not collision_api: collision_api = UsdPhysics.CollisionAPI.Apply(prim) physx_collision_api = PhysxSchema.PhysxCollisionAPI(prim) if not physx_collision_api: physx_collision_api = PhysxSchema.PhysxCollisionAPI.Apply(prim) self.set_contact_offset(name, prim, cfg["contact_offset"]) self.set_rest_offset(name, prim, cfg["rest_offset"]) def apply_articulation_settings(self, name, prim, cfg, force_articulation=False): from pxr import UsdPhysics, PhysxSchema stage = omni.usd.get_context().get_stage() is_articulation = False # check if is articulation prims = [prim] while len(prims) > 0: prim_tmp = prims.pop(0) articulation_api = UsdPhysics.ArticulationRootAPI.Get(stage, prim_tmp.GetPath()) physx_articulation_api = PhysxSchema.PhysxArticulationAPI.Get(stage, prim_tmp.GetPath()) if articulation_api or physx_articulation_api: is_articulation = True children_prims = prim_tmp.GetPrim().GetChildren() prims = prims + children_prims if not is_articulation and force_articulation: articulation_api = UsdPhysics.ArticulationRootAPI.Apply(prim) physx_articulation_api = PhysxSchema.PhysxArticulationAPI.Apply(prim) # parse through all children prims prims = [prim] while len(prims) > 0: cur_prim = prims.pop(0) rb = UsdPhysics.RigidBodyAPI.Get(stage, cur_prim.GetPath()) collision_body = UsdPhysics.CollisionAPI.Get(stage, cur_prim.GetPath()) articulation = UsdPhysics.ArticulationRootAPI.Get(stage, cur_prim.GetPath()) if rb: self.apply_rigid_body_settings(name, cur_prim, cfg, is_articulation) if collision_body: self.apply_rigid_shape_settings(name, cur_prim, cfg) if articulation: articulation_api = UsdPhysics.ArticulationRootAPI.Get(stage, cur_prim.GetPath()) physx_articulation_api = PhysxSchema.PhysxArticulationAPI.Get(stage, cur_prim.GetPath()) # enable self collisions enable_self_collisions = physx_articulation_api.GetEnabledSelfCollisionsAttr() if cfg["enable_self_collisions"] != -1: enable_self_collisions.Set(cfg["enable_self_collisions"]) self.set_articulation_position_iteration(name, cur_prim, cfg["solver_position_iteration_count"]) self.set_articulation_velocity_iteration(name, cur_prim, cfg["solver_velocity_iteration_count"]) self.set_articulation_sleep_threshold(name, cur_prim, cfg["sleep_threshold"]) self.set_articulation_stabilization_threshold(name, cur_prim, cfg["stabilization_threshold"]) children_prims = cur_prim.GetPrim().GetChildren() prims = prims + children_prims
18,615
Python
44.627451
122
0.641257
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/utils/config_utils/default_scene_params.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. 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. # # 3. Neither the name of the copyright holder 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 WARRANTIES, 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, INDIRECT, 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. default_physx_params = { ### Per-scene settings "use_gpu": False, "worker_thread_count": 4, "solver_type": 1, # 0: PGS, 1:TGS "bounce_threshold_velocity": 0.2, "friction_offset_threshold": 0.04, # A threshold of contact separation distance used to decide if a contact # point will experience friction forces. "friction_correlation_distance": 0.025, # Contact points can be merged into a single friction anchor if the # distance between the contacts is smaller than correlation distance. # disabling these can be useful for debugging "enable_sleeping": True, "enable_stabilization": True, # GPU buffers "gpu_max_rigid_contact_count": 512 * 1024, "gpu_max_rigid_patch_count": 80 * 1024, "gpu_found_lost_pairs_capacity": 1024, "gpu_found_lost_aggregate_pairs_capacity": 1024, "gpu_total_aggregate_pairs_capacity": 1024, "gpu_max_soft_body_contacts": 1024 * 1024, "gpu_max_particle_contacts": 1024 * 1024, "gpu_heap_capacity": 64 * 1024 * 1024, "gpu_temp_buffer_capacity": 16 * 1024 * 1024, "gpu_max_num_partitions": 8, ### Per-actor settings ( can override in actor_options ) "solver_position_iteration_count": 4, "solver_velocity_iteration_count": 1, "sleep_threshold": 0.0, # Mass-normalized kinetic energy threshold below which an actor may go to sleep. # Allowed range [0, max_float). "stabilization_threshold": 0.0, # Mass-normalized kinetic energy threshold below which an actor may # participate in stabilization. Allowed range [0, max_float). ### Per-body settings ( can override in actor_options ) "enable_gyroscopic_forces": False, "density": 1000.0, # density to be used for bodies that do not specify mass or density "max_depenetration_velocity": 100.0, ### Per-shape settings ( can override in actor_options ) "contact_offset": 0.02, "rest_offset": 0.001 } default_physics_material = { "static_friction": 1.0, "dynamic_friction": 1.0, "restitution": 0.0 } default_sim_params = { "gravity": [0.0, 0.0, -9.81], "dt": 1.0 / 60.0, "substeps": 1, "use_gpu_pipeline": True, "add_ground_plane": True, "add_distant_light": True, "use_flatcache": True, "enable_scene_query_support": False, "enable_cameras": False, "disable_contact_processing": False, "default_physics_material": default_physics_material } default_actor_options = { # -1 means use authored value from USD or default values from default_sim_params if not explicitly authored in USD. # If an attribute value is not explicitly authored in USD, add one with the value given here, # which overrides the USD default. "override_usd_defaults": False, "fixed_base": -1, "enable_self_collisions": -1, "enable_gyroscopic_forces": -1, "solver_position_iteration_count": -1, "solver_velocity_iteration_count": -1, "sleep_threshold": -1, "stabilization_threshold": -1, "max_depenetration_velocity": -1, "density": -1, "mass": -1, "contact_offset": -1, "rest_offset": -1 }
4,799
Python
41.105263
119
0.684101
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/utils/config_utils/path_utils.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. 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. # # 3. Neither the name of the copyright holder 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 WARRANTIES, 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, INDIRECT, 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. import carb from hydra.utils import to_absolute_path import os def is_valid_local_file(path): return os.path.isfile(path) def is_valid_ov_file(path): import omni.client result, entry = omni.client.stat(path) return result == omni.client.Result.OK def download_ov_file(source_path, target_path): import omni.client result = omni.client.copy(source_path, target_path) if result == omni.client.Result.OK: return True return False def break_ov_path(path): import omni.client return omni.client.break_url(path) def retrieve_checkpoint_path(path): print(to_absolute_path(path)) # check if it's a local path if is_valid_local_file(path): return to_absolute_path(path) # check if it's an OV path elif is_valid_ov_file(path): ov_path = break_ov_path(path) file_name = os.path.basename(ov_path.path) target_path = f"checkpoints/{file_name}" copy_to_local = download_ov_file(path, target_path) return to_absolute_path(target_path) else: carb.log_error(f"Invalid checkpoint path: {path}") return None
2,690
Python
38.573529
80
0.734944
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/utils/hydra_cfg/hydra_utils.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. 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. # # 3. Neither the name of the copyright holder 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 WARRANTIES, 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, INDIRECT, 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. import hydra from omegaconf import DictConfig, OmegaConf ## OmegaConf & Hydra Config # Resolvers used in hydra configs (see https://omegaconf.readthedocs.io/en/2.1_branch/usage.html#resolvers) OmegaConf.register_new_resolver('eq', lambda x, y: x.lower()==y.lower()) OmegaConf.register_new_resolver('contains', lambda x, y: x.lower() in y.lower()) OmegaConf.register_new_resolver('if', lambda pred, a, b: a if pred else b) # allows us to resolve default arguments which are copied in multiple places in the config. used primarily for # num_ensv OmegaConf.register_new_resolver('resolve_default', lambda default, arg: default if arg=='' else arg)
2,207
Python
51.571427
110
0.775714
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/utils/hydra_cfg/reformat.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. 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. # # 3. Neither the name of the copyright holder 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 WARRANTIES, 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, INDIRECT, 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. from omegaconf import DictConfig, OmegaConf from typing import Dict def omegaconf_to_dict(d: DictConfig)->Dict: """Converts an omegaconf DictConfig to a python Dict, respecting variable interpolation.""" ret = {} for k, v in d.items(): if isinstance(v, DictConfig): ret[k] = omegaconf_to_dict(v) else: ret[k] = v return ret def print_dict(val, nesting: int = -4, start: bool = True): """Outputs a nested dictionory.""" if type(val) == dict: if not start: print('') nesting += 4 for k in val: print(nesting * ' ', end='') print(k, end=': ') print_dict(val[k], nesting, start=False) else: print(val)
2,307
Python
41.74074
95
0.70958
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/utils/terrain_utils/terrain_utils.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. 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. # # 3. Neither the name of the copyright holder 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 WARRANTIES, 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, INDIRECT, 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. import numpy as np from numpy.random import choice from scipy import interpolate from math import sqrt from omni.isaac.core.prims import XFormPrim from pxr import UsdPhysics, Sdf, Gf, PhysxSchema def random_uniform_terrain(terrain, min_height, max_height, step=1, downsampled_scale=None,): """ Generate a uniform noise terrain Parameters terrain (SubTerrain): the terrain min_height (float): the minimum height of the terrain [meters] max_height (float): the maximum height of the terrain [meters] step (float): minimum height change between two points [meters] downsampled_scale (float): distance between two randomly sampled points ( musty be larger or equal to terrain.horizontal_scale) """ if downsampled_scale is None: downsampled_scale = terrain.horizontal_scale # switch parameters to discrete units min_height = int(min_height / terrain.vertical_scale) max_height = int(max_height / terrain.vertical_scale) step = int(step / terrain.vertical_scale) heights_range = np.arange(min_height, max_height + step, step) height_field_downsampled = np.random.choice(heights_range, (int(terrain.width * terrain.horizontal_scale / downsampled_scale), int( terrain.length * terrain.horizontal_scale / downsampled_scale))) x = np.linspace(0, terrain.width * terrain.horizontal_scale, height_field_downsampled.shape[0]) y = np.linspace(0, terrain.length * terrain.horizontal_scale, height_field_downsampled.shape[1]) f = interpolate.interp2d(y, x, height_field_downsampled, kind='linear') x_upsampled = np.linspace(0, terrain.width * terrain.horizontal_scale, terrain.width) y_upsampled = np.linspace(0, terrain.length * terrain.horizontal_scale, terrain.length) z_upsampled = np.rint(f(y_upsampled, x_upsampled)) terrain.height_field_raw += z_upsampled.astype(np.int16) return terrain def sloped_terrain(terrain, slope=1): """ Generate a sloped terrain Parameters: terrain (SubTerrain): the terrain slope (int): positive or negative slope Returns: terrain (SubTerrain): update terrain """ x = np.arange(0, terrain.width) y = np.arange(0, terrain.length) xx, yy = np.meshgrid(x, y, sparse=True) xx = xx.reshape(terrain.width, 1) max_height = int(slope * (terrain.horizontal_scale / terrain.vertical_scale) * terrain.width) terrain.height_field_raw[:, np.arange(terrain.length)] += (max_height * xx / terrain.width).astype(terrain.height_field_raw.dtype) return terrain def pyramid_sloped_terrain(terrain, slope=1, platform_size=1.): """ Generate a sloped terrain Parameters: terrain (terrain): the terrain slope (int): positive or negative slope platform_size (float): size of the flat platform at the center of the terrain [meters] Returns: terrain (SubTerrain): update terrain """ x = np.arange(0, terrain.width) y = np.arange(0, terrain.length) center_x = int(terrain.width / 2) center_y = int(terrain.length / 2) xx, yy = np.meshgrid(x, y, sparse=True) xx = (center_x - np.abs(center_x-xx)) / center_x yy = (center_y - np.abs(center_y-yy)) / center_y xx = xx.reshape(terrain.width, 1) yy = yy.reshape(1, terrain.length) max_height = int(slope * (terrain.horizontal_scale / terrain.vertical_scale) * (terrain.width / 2)) terrain.height_field_raw += (max_height * xx * yy).astype(terrain.height_field_raw.dtype) platform_size = int(platform_size / terrain.horizontal_scale / 2) x1 = terrain.width // 2 - platform_size x2 = terrain.width // 2 + platform_size y1 = terrain.length // 2 - platform_size y2 = terrain.length // 2 + platform_size min_h = min(terrain.height_field_raw[x1, y1], 0) max_h = max(terrain.height_field_raw[x1, y1], 0) terrain.height_field_raw = np.clip(terrain.height_field_raw, min_h, max_h) return terrain def discrete_obstacles_terrain(terrain, max_height, min_size, max_size, num_rects, platform_size=1.): """ Generate a terrain with gaps Parameters: terrain (terrain): the terrain max_height (float): maximum height of the obstacles (range=[-max, -max/2, max/2, max]) [meters] min_size (float): minimum size of a rectangle obstacle [meters] max_size (float): maximum size of a rectangle obstacle [meters] num_rects (int): number of randomly generated obstacles platform_size (float): size of the flat platform at the center of the terrain [meters] Returns: terrain (SubTerrain): update terrain """ # switch parameters to discrete units max_height = int(max_height / terrain.vertical_scale) min_size = int(min_size / terrain.horizontal_scale) max_size = int(max_size / terrain.horizontal_scale) platform_size = int(platform_size / terrain.horizontal_scale) (i, j) = terrain.height_field_raw.shape height_range = [-max_height, -max_height // 2, max_height // 2, max_height] width_range = range(min_size, max_size, 4) length_range = range(min_size, max_size, 4) for _ in range(num_rects): width = np.random.choice(width_range) length = np.random.choice(length_range) start_i = np.random.choice(range(0, i-width, 4)) start_j = np.random.choice(range(0, j-length, 4)) terrain.height_field_raw[start_i:start_i+width, start_j:start_j+length] = np.random.choice(height_range) x1 = (terrain.width - platform_size) // 2 x2 = (terrain.width + platform_size) // 2 y1 = (terrain.length - platform_size) // 2 y2 = (terrain.length + platform_size) // 2 terrain.height_field_raw[x1:x2, y1:y2] = 0 return terrain def wave_terrain(terrain, num_waves=1, amplitude=1.): """ Generate a wavy terrain Parameters: terrain (terrain): the terrain num_waves (int): number of sine waves across the terrain length Returns: terrain (SubTerrain): update terrain """ amplitude = int(0.5*amplitude / terrain.vertical_scale) if num_waves > 0: div = terrain.length / (num_waves * np.pi * 2) x = np.arange(0, terrain.width) y = np.arange(0, terrain.length) xx, yy = np.meshgrid(x, y, sparse=True) xx = xx.reshape(terrain.width, 1) yy = yy.reshape(1, terrain.length) terrain.height_field_raw += (amplitude*np.cos(yy / div) + amplitude*np.sin(xx / div)).astype( terrain.height_field_raw.dtype) return terrain def stairs_terrain(terrain, step_width, step_height): """ Generate a stairs Parameters: terrain (terrain): the terrain step_width (float): the width of the step [meters] step_height (float): the height of the step [meters] Returns: terrain (SubTerrain): update terrain """ # switch parameters to discrete units step_width = int(step_width / terrain.horizontal_scale) step_height = int(step_height / terrain.vertical_scale) num_steps = terrain.width // step_width height = step_height for i in range(num_steps): terrain.height_field_raw[i * step_width: (i + 1) * step_width, :] += height height += step_height return terrain def pyramid_stairs_terrain(terrain, step_width, step_height, platform_size=1.): """ Generate stairs Parameters: terrain (terrain): the terrain step_width (float): the width of the step [meters] step_height (float): the step_height [meters] platform_size (float): size of the flat platform at the center of the terrain [meters] Returns: terrain (SubTerrain): update terrain """ # switch parameters to discrete units step_width = int(step_width / terrain.horizontal_scale) step_height = int(step_height / terrain.vertical_scale) platform_size = int(platform_size / terrain.horizontal_scale) height = 0 start_x = 0 stop_x = terrain.width start_y = 0 stop_y = terrain.length while (stop_x - start_x) > platform_size and (stop_y - start_y) > platform_size: start_x += step_width stop_x -= step_width start_y += step_width stop_y -= step_width height += step_height terrain.height_field_raw[start_x: stop_x, start_y: stop_y] = height return terrain def stepping_stones_terrain(terrain, stone_size, stone_distance, max_height, platform_size=1., depth=-10): """ Generate a stepping stones terrain Parameters: terrain (terrain): the terrain stone_size (float): horizontal size of the stepping stones [meters] stone_distance (float): distance between stones (i.e size of the holes) [meters] max_height (float): maximum height of the stones (positive and negative) [meters] platform_size (float): size of the flat platform at the center of the terrain [meters] depth (float): depth of the holes (default=-10.) [meters] Returns: terrain (SubTerrain): update terrain """ # switch parameters to discrete units stone_size = int(stone_size / terrain.horizontal_scale) stone_distance = int(stone_distance / terrain.horizontal_scale) max_height = int(max_height / terrain.vertical_scale) platform_size = int(platform_size / terrain.horizontal_scale) height_range = np.arange(-max_height-1, max_height, step=1) start_x = 0 start_y = 0 terrain.height_field_raw[:, :] = int(depth / terrain.vertical_scale) if terrain.length >= terrain.width: while start_y < terrain.length: stop_y = min(terrain.length, start_y + stone_size) start_x = np.random.randint(0, stone_size) # fill first hole stop_x = max(0, start_x - stone_distance) terrain.height_field_raw[0: stop_x, start_y: stop_y] = np.random.choice(height_range) # fill row while start_x < terrain.width: stop_x = min(terrain.width, start_x + stone_size) terrain.height_field_raw[start_x: stop_x, start_y: stop_y] = np.random.choice(height_range) start_x += stone_size + stone_distance start_y += stone_size + stone_distance elif terrain.width > terrain.length: while start_x < terrain.width: stop_x = min(terrain.width, start_x + stone_size) start_y = np.random.randint(0, stone_size) # fill first hole stop_y = max(0, start_y - stone_distance) terrain.height_field_raw[start_x: stop_x, 0: stop_y] = np.random.choice(height_range) # fill column while start_y < terrain.length: stop_y = min(terrain.length, start_y + stone_size) terrain.height_field_raw[start_x: stop_x, start_y: stop_y] = np.random.choice(height_range) start_y += stone_size + stone_distance start_x += stone_size + stone_distance x1 = (terrain.width - platform_size) // 2 x2 = (terrain.width + platform_size) // 2 y1 = (terrain.length - platform_size) // 2 y2 = (terrain.length + platform_size) // 2 terrain.height_field_raw[x1:x2, y1:y2] = 0 return terrain def convert_heightfield_to_trimesh(height_field_raw, horizontal_scale, vertical_scale, slope_threshold=None): """ Convert a heightfield array to a triangle mesh represented by vertices and triangles. Optionally, corrects vertical surfaces above the provide slope threshold: If (y2-y1)/(x2-x1) > slope_threshold -> Move A to A' (set x1 = x2). Do this for all directions. B(x2,y2) /| / | / | (x1,y1)A---A'(x2',y1) Parameters: height_field_raw (np.array): input heightfield horizontal_scale (float): horizontal scale of the heightfield [meters] vertical_scale (float): vertical scale of the heightfield [meters] slope_threshold (float): the slope threshold above which surfaces are made vertical. If None no correction is applied (default: None) Returns: vertices (np.array(float)): array of shape (num_vertices, 3). Each row represents the location of each vertex [meters] triangles (np.array(int)): array of shape (num_triangles, 3). Each row represents the indices of the 3 vertices connected by this triangle. """ hf = height_field_raw num_rows = hf.shape[0] num_cols = hf.shape[1] y = np.linspace(0, (num_cols-1)*horizontal_scale, num_cols) x = np.linspace(0, (num_rows-1)*horizontal_scale, num_rows) yy, xx = np.meshgrid(y, x) if slope_threshold is not None: slope_threshold *= horizontal_scale / vertical_scale move_x = np.zeros((num_rows, num_cols)) move_y = np.zeros((num_rows, num_cols)) move_corners = np.zeros((num_rows, num_cols)) move_x[:num_rows-1, :] += (hf[1:num_rows, :] - hf[:num_rows-1, :] > slope_threshold) move_x[1:num_rows, :] -= (hf[:num_rows-1, :] - hf[1:num_rows, :] > slope_threshold) move_y[:, :num_cols-1] += (hf[:, 1:num_cols] - hf[:, :num_cols-1] > slope_threshold) move_y[:, 1:num_cols] -= (hf[:, :num_cols-1] - hf[:, 1:num_cols] > slope_threshold) move_corners[:num_rows-1, :num_cols-1] += (hf[1:num_rows, 1:num_cols] - hf[:num_rows-1, :num_cols-1] > slope_threshold) move_corners[1:num_rows, 1:num_cols] -= (hf[:num_rows-1, :num_cols-1] - hf[1:num_rows, 1:num_cols] > slope_threshold) xx += (move_x + move_corners*(move_x == 0)) * horizontal_scale yy += (move_y + move_corners*(move_y == 0)) * horizontal_scale # create triangle mesh vertices and triangles from the heightfield grid vertices = np.zeros((num_rows*num_cols, 3), dtype=np.float32) vertices[:, 0] = xx.flatten() vertices[:, 1] = yy.flatten() vertices[:, 2] = hf.flatten() * vertical_scale triangles = -np.ones((2*(num_rows-1)*(num_cols-1), 3), dtype=np.uint32) for i in range(num_rows - 1): ind0 = np.arange(0, num_cols-1) + i*num_cols ind1 = ind0 + 1 ind2 = ind0 + num_cols ind3 = ind2 + 1 start = 2*i*(num_cols-1) stop = start + 2*(num_cols-1) triangles[start:stop:2, 0] = ind0 triangles[start:stop:2, 1] = ind3 triangles[start:stop:2, 2] = ind1 triangles[start+1:stop:2, 0] = ind0 triangles[start+1:stop:2, 1] = ind2 triangles[start+1:stop:2, 2] = ind3 return vertices, triangles def add_terrain_to_stage(stage, vertices, triangles, position=None, orientation=None): num_faces = triangles.shape[0] terrain_mesh = stage.DefinePrim("/World/terrain", "Mesh") terrain_mesh.GetAttribute("points").Set(vertices) terrain_mesh.GetAttribute("faceVertexIndices").Set(triangles.flatten()) terrain_mesh.GetAttribute("faceVertexCounts").Set(np.asarray([3]*num_faces)) terrain = XFormPrim(prim_path="/World/terrain", name="terrain", position=position, orientation=orientation) UsdPhysics.CollisionAPI.Apply(terrain.prim) # collision_api = UsdPhysics.MeshCollisionAPI.Apply(terrain.prim) # collision_api.CreateApproximationAttr().Set("meshSimplification") physx_collision_api = PhysxSchema.PhysxCollisionAPI.Apply(terrain.prim) physx_collision_api.GetContactOffsetAttr().Set(0.02) physx_collision_api.GetRestOffsetAttr().Set(0.00) class SubTerrain: def __init__(self, terrain_name="terrain", width=256, length=256, vertical_scale=1.0, horizontal_scale=1.0): self.terrain_name = terrain_name self.vertical_scale = vertical_scale self.horizontal_scale = horizontal_scale self.width = width self.length = length self.height_field_raw = np.zeros((self.width, self.length), dtype=np.int16)
17,478
Python
42.917085
147
0.655166
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/utils/terrain_utils/create_terrain_demo.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. 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. # # 3. Neither the name of the copyright holder 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 WARRANTIES, 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, INDIRECT, 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. import os, sys SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(SCRIPT_DIR) import omni from omni.isaac.kit import SimulationApp import numpy as np import torch simulation_app = SimulationApp({"headless": False}) from abc import abstractmethod from omni.isaac.core.tasks import BaseTask from omni.isaac.core.prims import RigidPrimView, RigidPrim, XFormPrim from omni.isaac.core import World from omni.isaac.core.objects import DynamicSphere from omni.isaac.core.utils.prims import define_prim, get_prim_at_path from omni.isaac.core.utils.nucleus import find_nucleus_server from omni.isaac.core.utils.stage import add_reference_to_stage, get_current_stage from omni.isaac.core.materials import PreviewSurface from omni.isaac.cloner import GridCloner from pxr import UsdPhysics, UsdLux, UsdShade, Sdf, Gf, UsdGeom, PhysxSchema from terrain_utils import * class TerrainCreation(BaseTask): def __init__(self, name, num_envs, num_per_row, env_spacing, config=None, offset=None,) -> None: BaseTask.__init__(self, name=name, offset=offset) self._num_envs = num_envs self._num_per_row = num_per_row self._env_spacing = env_spacing self._device = "cpu" self._cloner = GridCloner(self._env_spacing, self._num_per_row) self._cloner.define_base_env(self.default_base_env_path) define_prim(self.default_zero_env_path) @property def default_base_env_path(self): return "/World/envs" @property def default_zero_env_path(self): return f"{self.default_base_env_path}/env_0" def set_up_scene(self, scene) -> None: self._stage = get_current_stage() distantLight = UsdLux.DistantLight.Define(self._stage, Sdf.Path("/World/DistantLight")) distantLight.CreateIntensityAttr(2000) self.get_terrain() self.get_ball() super().set_up_scene(scene) prim_paths = self._cloner.generate_paths("/World/envs/env", self._num_envs) print(f"cloning {self._num_envs} environments...") self._env_pos = self._cloner.clone( source_prim_path="/World/envs/env_0", prim_paths=prim_paths ) return def get_terrain(self): # create all available terrain types num_terains = 8 terrain_width = 12. terrain_length = 12. horizontal_scale = 0.25 # [m] vertical_scale = 0.005 # [m] num_rows = int(terrain_width/horizontal_scale) num_cols = int(terrain_length/horizontal_scale) heightfield = np.zeros((num_terains*num_rows, num_cols), dtype=np.int16) def new_sub_terrain(): return SubTerrain(width=num_rows, length=num_cols, vertical_scale=vertical_scale, horizontal_scale=horizontal_scale) heightfield[0:num_rows, :] = random_uniform_terrain(new_sub_terrain(), min_height=-0.2, max_height=0.2, step=0.2, downsampled_scale=0.5).height_field_raw heightfield[num_rows:2*num_rows, :] = sloped_terrain(new_sub_terrain(), slope=-0.5).height_field_raw heightfield[2*num_rows:3*num_rows, :] = pyramid_sloped_terrain(new_sub_terrain(), slope=-0.5).height_field_raw heightfield[3*num_rows:4*num_rows, :] = discrete_obstacles_terrain(new_sub_terrain(), max_height=0.5, min_size=1., max_size=5., num_rects=20).height_field_raw heightfield[4*num_rows:5*num_rows, :] = wave_terrain(new_sub_terrain(), num_waves=2., amplitude=1.).height_field_raw heightfield[5*num_rows:6*num_rows, :] = stairs_terrain(new_sub_terrain(), step_width=0.75, step_height=-0.5).height_field_raw heightfield[6*num_rows:7*num_rows, :] = pyramid_stairs_terrain(new_sub_terrain(), step_width=0.75, step_height=-0.5).height_field_raw heightfield[7*num_rows:8*num_rows, :] = stepping_stones_terrain(new_sub_terrain(), stone_size=1., stone_distance=1., max_height=0.5, platform_size=0.).height_field_raw vertices, triangles = convert_heightfield_to_trimesh(heightfield, horizontal_scale=horizontal_scale, vertical_scale=vertical_scale, slope_threshold=1.5) position = np.array([-6.0, 48.0, 0]) orientation = np.array([0.70711, 0.0, 0.0, -0.70711]) add_terrain_to_stage(stage=self._stage, vertices=vertices, triangles=triangles, position=position, orientation=orientation) def get_ball(self): ball = DynamicSphere(prim_path=self.default_zero_env_path + "/ball", name="ball", translation=np.array([0.0, 0.0, 1.0]), mass=0.5, radius=0.2,) def post_reset(self): for i in range(self._num_envs): ball_prim = self._stage.GetPrimAtPath(f"{self.default_base_env_path}/env_{i}/ball") color = 0.5 + 0.5 * np.random.random(3) visual_material = PreviewSurface(prim_path=f"{self.default_base_env_path}/env_{i}/ball/Looks/visual_material", color=color) binding_api = UsdShade.MaterialBindingAPI(ball_prim) binding_api.Bind(visual_material.material, bindingStrength=UsdShade.Tokens.strongerThanDescendants) def get_observations(self): pass def calculate_metrics(self) -> None: pass def is_done(self) -> None: pass if __name__ == "__main__": world = World( stage_units_in_meters=1.0, rendering_dt=1.0/60.0, backend="torch", device="cpu", ) num_envs = 800 num_per_row = 80 env_spacing = 0.56*2 terrain_creation_task = TerrainCreation(name="TerrainCreation", num_envs=num_envs, num_per_row=num_per_row, env_spacing=env_spacing, ) world.add_task(terrain_creation_task) world.reset() while simulation_app.is_running(): if world.is_playing(): if world.current_time_step_index == 0: world.reset(soft=True) world.step(render=True) else: world.step(render=True) simulation_app.close()
7,869
Python
43.213483
166
0.650654
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/utils/usd_utils/create_instanceable_assets.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. 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. # # 3. Neither the name of the copyright holder 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 WARRANTIES, 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, INDIRECT, 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. import omni.usd import omni.client from pxr import UsdGeom, Sdf def update_reference(source_prim_path, source_reference_path, target_reference_path): stage = omni.usd.get_context().get_stage() prims = [stage.GetPrimAtPath(source_prim_path)] while len(prims) > 0: prim = prims.pop(0) prim_spec = stage.GetRootLayer().GetPrimAtPath(prim.GetPath()) reference_list = prim_spec.referenceList refs = reference_list.GetAddedOrExplicitItems() if len(refs) > 0: for ref in refs: if ref.assetPath == source_reference_path: prim.GetReferences().RemoveReference(ref) prim.GetReferences().AddReference(assetPath=target_reference_path, primPath=prim.GetPath()) prims = prims + prim.GetChildren() def create_parent_xforms(asset_usd_path, source_prim_path, save_as_path=None): """ Adds a new UsdGeom.Xform prim for each Mesh/Geometry prim under source_prim_path. Moves material assignment to new parent prim if any exists on the Mesh/Geometry prim. Args: asset_usd_path (str): USD file path for asset source_prim_path (str): USD path of root prim save_as_path (str): USD file path for modified USD stage. Defaults to None, will save in same file. """ omni.usd.get_context().open_stage(asset_usd_path) stage = omni.usd.get_context().get_stage() prims = [stage.GetPrimAtPath(source_prim_path)] edits = Sdf.BatchNamespaceEdit() while len(prims) > 0: prim = prims.pop(0) print(prim) if prim.GetTypeName() in ["Mesh", "Capsule", "Sphere", "Box"]: new_xform = UsdGeom.Xform.Define(stage, str(prim.GetPath()) + "_xform") print(prim, new_xform) edits.Add(Sdf.NamespaceEdit.Reparent(prim.GetPath(), new_xform.GetPath(), 0)) continue children_prims = prim.GetChildren() prims = prims + children_prims stage.GetRootLayer().Apply(edits) if save_as_path is None: omni.usd.get_context().save_stage() else: omni.usd.get_context().save_as_stage(save_as_path) def convert_asset_instanceable(asset_usd_path, source_prim_path, save_as_path=None, create_xforms=True): """ Makes all mesh/geometry prims instanceable. Can optionally add UsdGeom.Xform prim as parent for all mesh/geometry prims. Makes a copy of the asset USD file, which will be used for referencing. Updates asset file to convert all parent prims of mesh/geometry prims to reference cloned USD file. Args: asset_usd_path (str): USD file path for asset source_prim_path (str): USD path of root prim save_as_path (str): USD file path for modified USD stage. Defaults to None, will save in same file. create_xforms (bool): Whether to add new UsdGeom.Xform prims to mesh/geometry prims. """ if create_xforms: create_parent_xforms(asset_usd_path, source_prim_path, save_as_path) asset_usd_path = save_as_path instance_usd_path = ".".join(asset_usd_path.split(".")[:-1]) + "_meshes.usd" omni.client.copy(asset_usd_path, instance_usd_path) omni.usd.get_context().open_stage(asset_usd_path) stage = omni.usd.get_context().get_stage() prims = [stage.GetPrimAtPath(source_prim_path)] while len(prims) > 0: prim = prims.pop(0) if prim: if prim.GetTypeName() in ["Mesh", "Capsule", "Sphere", "Box"]: parent_prim = prim.GetParent() if parent_prim and not parent_prim.IsInstance(): parent_prim.GetReferences().AddReference(assetPath=instance_usd_path, primPath=str(parent_prim.GetPath())) parent_prim.SetInstanceable(True) continue children_prims = prim.GetChildren() prims = prims + children_prims if save_as_path is None: omni.usd.get_context().save_stage() else: omni.usd.get_context().save_as_stage(save_as_path)
5,639
Python
43.761904
126
0.675829
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/runs/SwerveCS/config.yaml
task: name: SwerveCS physics_engine: ${..physics_engine} env: numEnvs: 36 envSpacing: 20 resetDist: 3.0 clipObservations: 1.0 clipActions: 1.0 controlFrequencyInv: 12 control: stiffness: 85.0 damping: 2.0 actionScale: 13.5 episodeLength_s: 15 sim: dt: 0.01 use_gpu_pipeline: ${eq:${...pipeline},"gpu"} gravity: - 0.0 - 0.0 - -9.81 add_ground_plane: true add_distant_light: true use_flatcache: true enable_scene_query_support: false default_physics_material: static_friction: 1.0 dynamic_friction: 1.0 restitution: 0.0 physx: worker_thread_count: ${....num_threads} solver_type: ${....solver_type} use_gpu: ${eq:${....sim_device},"gpu"} solver_position_iteration_count: 4 solver_velocity_iteration_count: 4 contact_offset: 0.02 rest_offset: 0.001 bounce_threshold_velocity: 0.2 friction_offset_threshold: 0.04 friction_correlation_distance: 0.025 enable_sleeping: true enable_stabilization: true max_depenetration_velocity: 100.0 gpu_max_rigid_contact_count: 524288 gpu_max_rigid_patch_count: 163840 gpu_found_lost_pairs_capacity: 4194304 gpu_found_lost_aggregate_pairs_capacity: 33554432 gpu_total_aggregate_pairs_capacity: 4194304 gpu_max_soft_body_contacts: 1048576 gpu_max_particle_contacts: 1048576 gpu_heap_capacity: 134217728 gpu_temp_buffer_capacity: 33554432 gpu_max_num_partitions: 8 SwerveCS: override_usd_defaults: false fixed_base: false enable_self_collisions: false enable_gyroscopic_forces: true solver_velocity_iteration_count: 8 sleep_threshold: 0.005 stabilization_threshold: 0.001 density: -1 max_depenetration_velocity: 100.0 contact_offset: 0.02 rest_offset: 0.001 train: params: seed: ${...seed} algo: name: a2c_continuous model: name: continuous_a2c_logstd network: name: actor_critic separate: false space: continuous: mu_activation: None sigma_activation: None mu_init: name: default sigma_init: name: const_initializer val: 0 fixed_sigma: true mlp: units: - 256 - 128 - 64 activation: elu d2rl: false initializer: name: default regularizer: name: None load_checkpoint: ${if:${...checkpoint},True,False} load_path: ${...checkpoint} config: name: ${resolve_default:SwerveCS,${....experiment}} full_experiment_name: ${.name} device: ${....rl_device} device_name: ${....rl_device} env_name: rlgpu ppo: true mixed_precision: false normalize_input: true normalize_value: true num_actors: ${....task.env.numEnvs} reward_shaper: scale_value: 0.1 normalize_advantage: true gamma: 0.99 tau: 0.95 learning_rate: 0.0003 lr_schedule: adaptive kl_threshold: 0.008 score_to_win: 20000 max_epochs: 10000 save_best_after: 50 save_frequency: 25 grad_norm: 1.0 entropy_coef: 0.0 truncate_grads: true e_clip: 0.2 horizon_length: 10 minibatch_size: 360 mini_epochs: 8 critic_coef: 4 clip_value: true seq_len: 4 bounds_loss_coef: 0.0001 task_name: ${task.name} experiment: '' num_envs: '' seed: 42 torch_deterministic: false max_iterations: '' physics_engine: physx pipeline: gpu sim_device: gpu device_id: 0 rl_device: cuda:0 num_threads: 4 solver_type: 1 test: true checkpoint: /root/edna/isaac/Swervesim/swervesim/runs/SwerveCS/nn/last_SwerveCS_ep_750_rew_166.53838.pth headless: false wandb_activate: false wandb_group: '' wandb_name: ${train.params.config.name} wandb_entity: '' wandb_project: swervesim
3,989
YAML
24.741935
104
0.61093
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/runs/Swerve/config.yaml
task: name: Swerve physics_engine: ${..physics_engine} env: numEnvs: 324 envSpacing: 20.0 resetDist: 3.0 clipObservations: 5.0 clipActions: 1.0 controlFrequencyInv: 12 baseInitState: pos: - 0.0 - 0.0 - 0.62 rot: - 0.0 - 0.0 - 0.0 - 1.0 vLinear: - 0.0 - 0.0 - 0.0 vAngular: - 0.0 - 0.0 - 0.0 control: stiffness: 85.0 damping: 2.0 actionScale: 13.5 episodeLength_s: 50 sim: dt: 0.0083 use_gpu_pipeline: ${eq:${...pipeline},"gpu"} gravity: - 0.0 - 0.0 - -9.81 add_ground_plane: true add_distant_light: true use_flatcache: true enable_scene_query_support: false default_physics_material: static_friction: 1.0 dynamic_friction: 1.0 restitution: 0.0 physx: worker_thread_count: ${....num_threads} solver_type: ${....solver_type} use_gpu: ${eq:${....sim_device},"gpu"} solver_position_iteration_count: 4 solver_velocity_iteration_count: 4 contact_offset: 0.02 rest_offset: 0.001 bounce_threshold_velocity: 0.2 friction_offset_threshold: 0.04 friction_correlation_distance: 0.025 enable_sleeping: true enable_stabilization: true max_depenetration_velocity: 100.0 gpu_max_rigid_contact_count: 524288 gpu_max_rigid_patch_count: 81920 gpu_found_lost_pairs_capacity: 1024 gpu_found_lost_aggregate_pairs_capacity: 262144 gpu_total_aggregate_pairs_capacity: 1024 gpu_max_soft_body_contacts: 1048576 gpu_max_particle_contacts: 1048576 gpu_heap_capacity: 67108864 gpu_temp_buffer_capacity: 16777216 gpu_max_num_partitions: 8 Swerve: override_usd_defaults: false fixed_base: false enable_self_collisions: false enable_gyroscopic_forces: true solver_velocity_iteration_count: 8 sleep_threshold: 0.005 stabilization_threshold: 0.001 density: -1 max_depenetration_velocity: 100.0 contact_offset: 0.02 rest_offset: 0.001 train: params: seed: ${...seed} algo: name: a2c_continuous model: name: continuous_a2c_logstd network: name: actor_critic separate: false space: continuous: mu_activation: None sigma_activation: None mu_init: name: default sigma_init: name: const_initializer val: 0 fixed_sigma: true mlp: units: - 256 - 128 - 64 activation: elu d2rl: false initializer: name: default regularizer: name: None load_checkpoint: ${if:${...checkpoint},True,False} load_path: ${...checkpoint} config: name: ${resolve_default:Swerve,${....experiment}} full_experiment_name: ${.name} device: ${....rl_device} device_name: ${....rl_device} env_name: rlgpu ppo: true mixed_precision: false normalize_input: true normalize_value: true num_actors: ${....task.env.numEnvs} reward_shaper: scale_value: 0.1 normalize_advantage: true gamma: 0.99 tau: 0.95 learning_rate: 0.0003 lr_schedule: adaptive kl_threshold: 0.008 score_to_win: 20000 max_epochs: 10000 save_best_after: 50 save_frequency: 25 grad_norm: 1.0 entropy_coef: 0.0 truncate_grads: true e_clip: 0.2 horizon_length: 10 minibatch_size: 360 mini_epochs: 8 critic_coef: 4 clip_value: true seq_len: 4 bounds_loss_coef: 0.0001 task_name: ${task.name} experiment: '' num_envs: '' seed: 42 torch_deterministic: false max_iterations: '' physics_engine: physx pipeline: gpu sim_device: gpu device_id: 0 rl_device: cuda:0 num_threads: 4 solver_type: 1 test: false checkpoint: '' headless: false wandb_activate: false wandb_group: '' wandb_name: ${train.params.config.name} wandb_entity: '' wandb_project: omniisaacgymenv
4,124
YAML
22.843931
55
0.586081
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/runs/SwerveK/config.yaml
task: name: SwerveK physics_engine: ${..physics_engine} env: numEnvs: 36 envSpacing: 20.0 resetDist: 3.0 clipObservations: 5.0 clipActions: 1.0 controlFrequencyInv: 12 baseInitState: pos: - 0.0 - 0.0 - 0.62 rot: - 0.0 - 0.0 - 0.0 - 1.0 vLinear: - 0.0 - 0.0 - 0.0 vAngular: - 0.0 - 0.0 - 0.0 control: stiffness: 85.0 damping: 2.0 actionScale: 13.5 episodeLength_s: 50 sim: dt: 0.0083 use_gpu_pipeline: ${eq:${...pipeline},"gpu"} gravity: - 0.0 - 0.0 - -9.81 add_ground_plane: true add_distant_light: true use_flatcache: true enable_scene_query_support: false default_physics_material: static_friction: 1.0 dynamic_friction: 1.0 restitution: 0.0 physx: worker_thread_count: ${....num_threads} solver_type: ${....solver_type} use_gpu: ${eq:${....sim_device},"gpu"} solver_position_iteration_count: 4 solver_velocity_iteration_count: 4 contact_offset: 0.02 rest_offset: 0.001 bounce_threshold_velocity: 0.2 friction_offset_threshold: 0.04 friction_correlation_distance: 0.025 enable_sleeping: true enable_stabilization: true max_depenetration_velocity: 100.0 gpu_max_rigid_contact_count: 524288 gpu_max_rigid_patch_count: 81920 gpu_found_lost_pairs_capacity: 1024 gpu_found_lost_aggregate_pairs_capacity: 262144 gpu_total_aggregate_pairs_capacity: 1024 gpu_max_soft_body_contacts: 1048576 gpu_max_particle_contacts: 1048576 gpu_heap_capacity: 67108864 gpu_temp_buffer_capacity: 16777216 gpu_max_num_partitions: 8 SwerveK: override_usd_defaults: false fixed_base: false enable_self_collisions: false enable_gyroscopic_forces: true solver_velocity_iteration_count: 8 sleep_threshold: 0.005 stabilization_threshold: 0.001 density: -1 max_depenetration_velocity: 100.0 contact_offset: 0.02 rest_offset: 0.001 train: params: seed: ${...seed} algo: name: a2c_continuous model: name: continuous_a2c_logstd network: name: actor_critic separate: false space: continuous: mu_activation: None sigma_activation: None mu_init: name: default sigma_init: name: const_initializer val: 0 fixed_sigma: true mlp: units: - 256 - 128 - 64 activation: elu d2rl: false initializer: name: default regularizer: name: None load_checkpoint: ${if:${...checkpoint},True,False} load_path: ${...checkpoint} config: name: ${resolve_default:SwerveK,${....experiment}} full_experiment_name: ${.name} device: ${....rl_device} device_name: ${....rl_device} env_name: rlgpu ppo: true mixed_precision: false normalize_input: true normalize_value: true num_actors: ${....task.env.numEnvs} reward_shaper: scale_value: 0.1 normalize_advantage: true gamma: 0.99 tau: 0.95 learning_rate: 0.0003 lr_schedule: adaptive kl_threshold: 0.008 score_to_win: 20000 max_epochs: 10000 save_best_after: 50 save_frequency: 25 grad_norm: 1.0 entropy_coef: 0.0 truncate_grads: true e_clip: 0.2 horizon_length: 10 minibatch_size: 360 mini_epochs: 8 critic_coef: 4 clip_value: true seq_len: 4 bounds_loss_coef: 0.0001 task_name: ${task.name} experiment: '' num_envs: '' seed: 42 torch_deterministic: false max_iterations: '' physics_engine: physx pipeline: gpu sim_device: gpu device_id: 0 rl_device: cuda:0 num_threads: 4 solver_type: 1 test: true checkpoint: /home/nitin/Documents/2023RobotROS/Swervesim/swervesim/runs/SwerveK/nn/Best_SwerveK.pth headless: false wandb_activate: false wandb_group: '' wandb_name: ${train.params.config.name} wandb_entity: '' wandb_project: omniisaacgymenv
4,210
YAML
23.34104
99
0.592162
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/robots/articulations/swerve.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. 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. # # 3. Neither the name of the copyright holder 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 WARRANTIES, 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, INDIRECT, 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. from typing import Optional import numpy as np import torch import omni.kit.commands from omni.isaac.urdf import _urdf from omni.isaac.core.prims import RigidPrimView from omni.isaac.core.robots.robot import Robot from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage from omni.isaac.core.utils.stage import get_current_stage import numpy as np import torch import os from pxr import PhysxSchema class Swerve(Robot): def __init__(self,prim_path,name,translation): self._name = name #self.prim_path = prim_path file_path = os.path.abspath(__file__) project_root_path = os.path.abspath(os.path.join(file_path, "../../../../../../")) root_path= os.path.join(project_root_path, "isaac/assets/swerve/swerve.usd") print(str(root_path)) print(prim_path) self._usd_path = root_path add_reference_to_stage(self._usd_path, prim_path) print(str(get_current_stage() )) super().__init__( prim_path=prim_path, name=name, translation=translation, orientation=None, articulation_controller=None, ) self._dof_names = ["front_left_axle_joint", "front_right_axle_joint", "rear_left_axle_joint", "rear_right_axle_joint", "front_left_wheel_joint", "front_right_wheel_joint", "rear_left_wheel_joint", "rear_right_wheel_joint", ] @property def dof_names(self): return self._dof_names def set_swerve_properties(self, stage, prim): for link_prim in prim.GetChildren(): if link_prim.HasAPI(PhysxSchema.PhysxRigidBodyAPI): rb = PhysxSchema.PhysxRigidBodyAPI.Get(stage, link_prim.GetPrimPath()) rb.GetDisableGravityAttr().Set(False) rb.GetRetainAccelerationsAttr().Set(False) rb.GetLinearDampingAttr().Set(0.0) rb.GetMaxLinearVelocityAttr().Set(1000.0) rb.GetAngularDampingAttr().Set(0.0) rb.GetMaxAngularVelocityAttr().Set(64/np.pi*180)
3,885
Python
41.703296
90
0.665894
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/robots/articulations/views/charge_station_view.py
from typing import Optional from omni.isaac.core.articulations import ArticulationView from omni.isaac.core.prims import RigidPrimView import math import torch class ChargeStationView(ArticulationView): def __init__( self, prim_paths_expr: str, name: Optional[str] = "ChargeStationView", ) -> None: """[summary] """ super().__init__( prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False ) self.chargestation_base = RigidPrimView(prim_paths_expr="/World/envs/.*/ChargeStation", name="base_view", reset_xform_properties=False) # self.top = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field", name="field_view", reset_xform_properties=False) # self.red_ball_1 = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/Tennis_Ball___Red_08", name="redball[1]", reset_xform_properties=False) # self.red_ball_2 = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/Tennis_Ball___Red_09", name="redball[2]", reset_xform_properties=False) # self.red_ball_3 = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/Tennis_Ball___Red_10", name="redball[3]", reset_xform_properties=False) # self.red_ball_4 = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/Tennis_Ball___Red_11", name="redball[4]", reset_xform_properties=False) # self.red_ball_5 = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/Tennis_Ball___Red_12", name="redball[5]", reset_xform_properties=False) # self.red_ball_6 = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/Tennis_Ball___Red_13", name="redball[6]", reset_xform_properties=False) # self.red_ball_7 = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/Tennis_Ball___Red_14", name="redball[7]", reset_xform_properties=False) # self.red_ball_8 = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/Tennis_Ball___Red_15", name="redball[8]", reset_xform_properties=False) # self.blue_ball_1 = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/Tennis_Ball___Blue_08", name="blueball[1]", reset_xform_properties=False) # self.blue_ball_2 = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/Tennis_Ball___Blue_09", name="blueball[2]", reset_xform_properties=False) # self.blue_ball_3 = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/Tennis_Ball___Blue_10", name="blueball[3]", reset_xform_properties=False) # self.blue_ball_4 = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/Tennis_Ball___Blue_11", name="blueball[4]", reset_xform_properties=False) # self.blue_ball_5 = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/Tennis_Ball___Blue_12", name="blueball[5]", reset_xform_properties=False) # self.blue_ball_6 = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/Tennis_Ball___Blue_13", name="blueball[6]", reset_xform_properties=False) # self.blue_ball_7 = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/Tennis_Ball___Blue_14", name="blueball[7]", reset_xform_properties=False) # self.blue_ball_8 = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/Tennis_Ball___Blue_15", name="blueball[8]", reset_xform_properties=False) # self.goal = RigidPrimView(prim_paths_expr="/World/envs/.*/Root/Rapid_React_Field/Group_1/THE_HUB_GE_22300_01/GE_22434", name="goal[1]", reset_xform_properties=False) def if_balanced(self, device): self.base_pose, self.base_orientation = self.chargestation_base.get_world_poses() tolerance = 0.03 output_roll = torch.tensor([1.0 if math.atan2(2*i[2]*i[0] - 2*i[1]*i[3], 1 - 2*i[2]*i[2] - 2*i[3]*i[3]) <= tolerance else 0.0 for i in self.base_orientation], device=device) return output_roll
4,200
Python
84.734692
181
0.684286
RoboEagles4828/edna2023/isaac/Swervesim/swervesim/robots/articulations/views/swerve_view.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. 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. # # 3. Neither the name of the copyright holder 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 WARRANTIES, 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, INDIRECT, 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. from typing import Optional from omni.isaac.core.articulations import ArticulationView from omni.isaac.core.prims import RigidPrimView import torch class SwerveView(ArticulationView): def __init__( self, prim_paths_expr: str, name: Optional[str] = "SwerveView", ) -> None: """[summary] """ super().__init__( prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False ) self._base = RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/swerve_chassis_link", name="base_view", reset_xform_properties=False) # self._axle = RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/.*_axle_link", name="axle_view", reset_xform_properties=False) # self._wheel = RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/.*_wheel_link", name="wheel_view", reset_xform_properties=False) self._axle = [ RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/front_left_axle_link", name="axle_view[0]", reset_xform_properties=False), RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/front_right_axle_link", name="axle_view[1]", reset_xform_properties=False), RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/rear_left_axle_link", name="axle_view[2]", reset_xform_properties=False), RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/rear_right_axle_link", name="axle_view[3]", reset_xform_properties=False) ] self._wheel = [ RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/front_left_wheel_link", name="wheel_view[0]", reset_xform_properties=False), RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/front_right_wheel_link", name="wheel_view[1]", reset_xform_properties=False), RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/rear_left_wheel_link", name="wheel_view[2]", reset_xform_properties=False), RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/rear_right_wheel_link", name="wheel_view[3]", reset_xform_properties=False) ] # self._axle = [ # RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/swerve_chassis_link/front_left_axle_joint", name="axle_view[0]", reset_xform_properties=False), # RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/swerve_chassis_link/front_right_axle_joint", name="axle_view[1]", reset_xform_properties=False), # RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/swerve_chassis_link/rear_left_axle_joint", name="axle_view[2]", reset_xform_properties=False), # RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/swerve_chassis_link/rear_right_axle_joint", name="axle_view[3]", reset_xform_properties=False) # ] # self._wheel = [ # RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/front_left_axle_link/front_left_wheel_joint", name="wheel_view[0]", reset_xform_properties=False), # RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/front_right_axle_link/front_right_wheel_joint", name="wheel_view[1]", reset_xform_properties=False), # RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/rear_left_axle_link/rear_left_wheel_joint", name="wheel_view[2]", reset_xform_properties=False), # RigidPrimView(prim_paths_expr="/World/envs/.*/swerve/rear_right_axle_link/rear_right_wheel_joint", name="wheel_view[3]", reset_xform_properties=False) # ] def get_axle_positions(self): axle_pose1, __ = self._axle[0].get_local_poses() axle_pose2, __ = self._axle[1].get_local_poses() axle_pose3, __ = self._axle[2].get_local_poses() axle_pose4, __ = self._axle[3].get_local_poses() tuple = (torch.transpose(axle_pose1, 0, 1), torch.transpose(axle_pose2, 0, 1), torch.transpose(axle_pose3, 0, 1), torch.transpose(axle_pose4, 0, 1) ) tuple_tensor = torch.cat(tuple) return torch.transpose(tuple_tensor, 0, 1) # def get_knee_transforms(self): # return self._knees.get_world_poses() # def is_knee_below_threshold(self, threshold, ground_heights=None): # knee_pos, _ = self._knees.get_world_poses() # knee_heights = knee_pos.view((-1, 4, 3))[:, :, 2] # if ground_heights is not None: # knee_heights -= ground_heights # return (knee_heights[:, 0] < threshold) | (knee_heights[:, 1] < threshold) | (knee_heights[:, 2] < threshold) | (knee_heights[:, 3] < threshold) # def is_base_below_threshold(self, threshold, ground_heights): # base_pos, _ = self.get_world_poses() # base_heights = base_pos[:, 2] # base_heights -= ground_heights # return (base_heights[:] < threshold)
6,450
Python
59.289719
167
0.664341
RoboEagles4828/edna2023/scripts/quickpub.py
#!/usr/bin/python3 import time import rclpy from rclpy.node import Node from sensor_msgs.msg import JointState from threading import Thread JOINT_NAMES = [ # Pneumatics 'arm_roller_bar_joint', 'top_slider_joint', 'top_gripper_left_arm_joint', 'bottom_gripper_left_arm_joint', # Wheels 'elevator_center_joint', 'bottom_intake_joint', ] class ROSNode(Node): def __init__(self): super().__init__('quickpublisher') self.publish_positions = [0.0]*6 self.publisher = self.create_publisher(JointState, "/real/real_arm_commands", 10) self.publishTimer = self.create_timer(0.5, self.publish) def publish(self): msg = JointState() msg.name = JOINT_NAMES msg.position = self.publish_positions self.publisher.publish(msg) def main(): rclpy.init() node = ROSNode() Thread(target=rclpy.spin, args=(node,)).start() while True: try: joint_index = int(input("Joint index: ")) position = float(input("Position: ")) node.publish_positions[joint_index] = position except: print("Invalid input") continue if __name__ == '__main__': main()
1,227
Python
25.127659
89
0.605542
RoboEagles4828/edna2023/scripts/config/omniverse.toml
[bookmarks] IsaacAssets = "omniverse://localhost/NVIDIA/Assets/Isaac/2022.2.1/Isaac" Scenarios = "omniverse://localhost/NVIDIA/Assets/Isaac/2022.2.1/Isaac/Samples/ROS2/Scenario" edna = "/workspaces/edna2023" localhost = "omniverse://localhost" [cache] data_dir = "/root/.cache/ov/Cache" proxy_cache_enabled = false proxy_cache_server = "" [connection_library] proxy_dict = "*#localhost:8891,f"
397
TOML
25.533332
92
0.743073
RoboEagles4828/edna2023/docker/developer/README.md
# Docker for Development This directory has the configuration for building the image used in the edna devcontainer. It uses the osrf ros humble image as a base and installs edna related software on top. When loading the devcontainer the common utils feature is used to update the user GID/UID to match local and setup zsh and other terminal nice to haves. **Common Utils**: `devcontainers/features/common-utils` \ **URL**: https://github.com/devcontainers/features/tree/main/src/common-utils # Build 1. Docker Login to github registry. [Guide](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry#authenticating-with-a-personal-access-token-classic) \ This will be used to push the image to the registry 2. Run `./build` to build the image. \ The script will prompt you if you would like to do a quick test or push to the registry.
897
Markdown
48.888886
210
0.782609
RoboEagles4828/edna2023/docker/jetson/README.md
# Jetson Docker Image
21
Markdown
20.999979
21
0.809524
RoboEagles4828/edna2023/docker/developer-isaac-ros/README.md
# Docker for isaac ros This directory has the configuration for building the image used for isaac utilities that require l4t. It uses the isaac ros common container as a base and installs edna related software on top. # Build 1. Docker Login to the nvidia NGC registry. [Guide](https://docs.nvidia.com/ngc/ngc-catalog-user-guide/index.html)\ This will be used to download nvidia images. 2. Docker Login to github registry. [Guide](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry#authenticating-with-a-personal-access-token-classic) \ This will be used to push the image to the registry 3. Run `./build` to build the image. \ The script will prompt you if you would like to do a quick test or push to the registry.
780
Markdown
59.076919
210
0.783333
RoboEagles4828/edna2023/docker/jetson-isaac-ros/README.md
# Jetson Docker Image with Isaac ROS
36
Markdown
35.999964
36
0.805556
RoboEagles4828/edna2023/rio/robot.py
import logging import wpilib import threading import traceback import time import os, inspect from hardware_interface.drivetrain import DriveTrain from hardware_interface.joystick import Joystick from hardware_interface.armcontroller import ArmController from dds.dds import DDS_Publisher, DDS_Subscriber EMABLE_ENCODER = True ENABLE_JOY = True ENABLE_DRIVE = True ENABLE_ARM = True ENABLE_STAGE_BROADCASTER = True # Global Variables frc_stage = "DISABLED" fms_attached = False stop_threads = False drive_train : DriveTrain = None joystick : Joystick = None arm_controller : ArmController = None # Logging format = "%(asctime)s: %(message)s" logging.basicConfig(format=format, level=logging.INFO, datefmt="%H:%M:%S") # XML Path for DDS configuration curr_path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) xml_path = os.path.join(curr_path, "dds/xml/ROS_RTI.xml") ############################################ ## Hardware def initDriveTrain(): global drive_train if drive_train == None: drive_train = DriveTrain() logging.info("Success: DriveTrain created") return drive_train def initJoystick(): global joystick if joystick == None: joystick = Joystick() logging.info("Success: Joystick created") return joystick def initArmController(): global arm_controller if arm_controller == None: arm_controller = ArmController() logging.info("Success: ArmController created") return arm_controller def initDDS(ddsAction, participantName, actionName): dds = None with rti_init_lock: dds = ddsAction(xml_path, participantName, actionName) return dds ############################################ ############################################ ## Threads def threadLoop(name, dds, action): logging.info(f"Starting {name} thread") global stop_threads global frc_stage try: while stop_threads == False: if (frc_stage == 'AUTON' and name != "joystick") or (name in ["encoder", "stage-broadcaster"]) or (frc_stage == 'TELEOP'): action(dds) time.sleep(20/1000) except Exception as e: logging.error(f"An issue occured with the {name} thread") logging.error(e) logging.error(traceback.format_exc()) logging.info(f"Closing {name} thread") dds.close() # Generic Start Thread Function def startThread(name) -> threading.Thread | None: thread = None if name == "encoder": thread = threading.Thread(target=encoderThread, daemon=True) elif name == "command": thread = threading.Thread(target=commandThread, daemon=True) elif name == "arm-command": thread = threading.Thread(target=armThread, daemon=True) elif name == "joystick": thread = threading.Thread(target=joystickThread, daemon=True) elif name == "stage-broadcaster": thread = threading.Thread(target=stageBroadcasterThread, daemon=True) thread.start() return thread # Locks rti_init_lock = threading.Lock() drive_train_lock = threading.Lock() arm_controller_lock = threading.Lock() ############################################ ################## ENCODER ################## ENCODER_PARTICIPANT_NAME = "ROS2_PARTICIPANT_LIB::encoder_info" ENCODER_WRITER_NAME = "encoder_info_publisher::encoder_info_writer" def encoderThread(): encoder_publisher = initDDS(DDS_Publisher, ENCODER_PARTICIPANT_NAME, ENCODER_WRITER_NAME) threadLoop('encoder', encoder_publisher, encoderAction) def encoderAction(publisher): # TODO: Make these some sort of null value to identify lost data data = { 'name': [], 'position': [], 'velocity': [] } global drive_train with drive_train_lock: if ENABLE_DRIVE: drive_data = drive_train.getEncoderData() data['name'] += drive_data['name'] data['position'] += drive_data['position'] data['velocity'] += drive_data['velocity'] global arm_controller with arm_controller_lock: if ENABLE_ARM: arm_data = arm_controller.getEncoderData() data['name'] += arm_data['name'] data['position'] += arm_data['position'] data['velocity'] += arm_data['velocity'] publisher.write(data) ############################################ ################## COMMAND ################## COMMAND_PARTICIPANT_NAME = "ROS2_PARTICIPANT_LIB::joint_commands" COMMAND_WRITER_NAME = "isaac_joint_commands_subscriber::joint_commands_reader" def commandThread(): command_subscriber = initDDS(DDS_Subscriber, COMMAND_PARTICIPANT_NAME, COMMAND_WRITER_NAME) threadLoop('command', command_subscriber, commandAction) def commandAction(subscriber : DDS_Subscriber): data = subscriber.read() global drive_train with drive_train_lock: drive_train.sendCommands(data) ############################################ ################## ARM ################## ARM_COMMAND_PARTICIPANT_NAME = "ROS2_PARTICIPANT_LIB::arm_commands" ARM_COMMAND_WRITER_NAME = "isaac_arm_commands_subscriber::arm_commands_reader" def armThread(): arm_command_subscriber = initDDS(DDS_Subscriber, ARM_COMMAND_PARTICIPANT_NAME, ARM_COMMAND_WRITER_NAME) threadLoop('arm', arm_command_subscriber, armAction) def armAction(subscriber : DDS_Subscriber): data = subscriber.read() global arm_controller with arm_controller_lock: arm_controller.sendCommands(data) ############################################ ################## JOYSTICK ################## JOYSTICK_PARTICIPANT_NAME = "ROS2_PARTICIPANT_LIB::joystick" JOYSTICK_WRITER_NAME = "joystick_data_publisher::joystick_data_writer" def joystickThread(): joystick_publisher = initDDS(DDS_Publisher, JOYSTICK_PARTICIPANT_NAME, JOYSTICK_WRITER_NAME) threadLoop('joystick', joystick_publisher, joystickAction) def joystickAction(publisher : DDS_Publisher): if frc_stage == "TELEOP": global joystick data = None try: data = joystick.getData() except: logging.warn("No joystick data could be fetched!") initJoystick() publisher.write(data) ############################################ ################## STAGE ################## STAGE_PARTICIPANT_NAME = "ROS2_PARTICIPANT_LIB::stage_broadcaster" STAGE_WRITER_NAME = "stage_publisher::stage_writer" def stageBroadcasterThread(): stage_publisher = initDDS(DDS_Publisher, STAGE_PARTICIPANT_NAME, STAGE_WRITER_NAME) threadLoop('stage-broadcaster', stage_publisher, stageBroadcasterAction) def stageBroadcasterAction(publisher : DDS_Publisher): global frc_stage global fms_attached is_disabled = wpilib.DriverStation.isDisabled() publisher.write({ "data": f"{frc_stage}|{fms_attached}|{is_disabled}" }) ############################################ ######### Robot Class ######### class EdnaRobot(wpilib.TimedRobot): def robotInit(self): self.use_threading = True wpilib.CameraServer.launch() logging.warning("Running in simulation!") if wpilib.RobotBase.isSimulation() else logging.info("Running in real!") self.drive_train = initDriveTrain() self.joystick = initJoystick() self.arm_controller = initArmController() self.threads = [] if self.use_threading: logging.info("Initializing Threads") global stop_threads stop_threads = False if ENABLE_DRIVE: self.threads.append({"name": "command", "thread": startThread("command") }) if ENABLE_ARM: self.threads.append({"name": "arm-command", "thread": startThread("arm-command")}) if ENABLE_JOY: self.threads.append({"name": "joystick", "thread": startThread("joystick") }) if EMABLE_ENCODER: self.threads.append({"name": "encoder", "thread": startThread("encoder") }) if ENABLE_STAGE_BROADCASTER: self.threads.append({"name": "stage-broadcaster", "thread": startThread("stage-broadcaster") }) else: self.encoder_publisher = DDS_Publisher(xml_path, ENCODER_PARTICIPANT_NAME, ENCODER_WRITER_NAME) self.joystick_publisher = DDS_Publisher(xml_path, JOYSTICK_PARTICIPANT_NAME, JOYSTICK_WRITER_NAME) self.command_subscriber = DDS_Subscriber(xml_path, COMMAND_PARTICIPANT_NAME, COMMAND_WRITER_NAME) self.arm_command_subscriber = DDS_Subscriber(xml_path, ARM_COMMAND_PARTICIPANT_NAME, ARM_COMMAND_WRITER_NAME) self.stage_publisher = DDS_Publisher(xml_path, STAGE_PARTICIPANT_NAME, STAGE_WRITER_NAME) # Auton def autonomousInit(self): logging.info("Entering Auton") global frc_stage frc_stage = "AUTON" def autonomousPeriodic(self): global fms_attached fms_attached = wpilib.DriverStation.isFMSAttached() if self.use_threading: self.manageThreads() else: self.doActions() def autonomousExit(self): logging.info("Exiting Auton") global frc_stage frc_stage = "AUTON" # Teleop def teleopInit(self): logging.info("Entering Teleop") global frc_stage frc_stage = "TELEOP" def teleopPeriodic(self): global fms_attached fms_attached = wpilib.DriverStation.isFMSAttached() if self.use_threading: self.manageThreads() else: self.doActions() def teleopExit(self): logging.info("Exiting Teleop") global frc_stage frc_stage = "DISABLED" with drive_train_lock: drive_train.stop() with arm_controller_lock: arm_controller.stop() def manageThreads(self): # Check all threads and make sure they are alive for thread in self.threads: if thread["thread"].is_alive() == False: # If this is the command thread, we need to stop the robot if thread["name"] == "command": logging.warning(f"Stopping robot due to command thread failure") with drive_train_lock: drive_train.stop() with arm_controller_lock: arm_controller.stop() logging.warning(f"Thread {thread['name']} is not alive, restarting...") thread["thread"] = startThread(thread["name"]) def doActions(self): encoderAction(self.encoder_publisher) commandAction(self.command_subscriber) armAction(self.arm_command_subscriber) joystickAction(self.joystick_publisher) stageBroadcasterAction(self.stage_publisher) # Is this needed? def stopThreads(self): global stop_threads stop_threads = True for thread in self.threads: thread.join() logging.info('All Threads Stopped') if __name__ == '__main__': wpilib.run(EdnaRobot)
11,010
Python
31.967066
136
0.622797
RoboEagles4828/edna2023/rio/physics.py
import wpilib import wpilib.simulation import ctre from pyfrc.physics import drivetrains from pyfrc.physics.core import PhysicsInterface from sim.talonFxSim import TalonFxSim from sim.cancoderSim import CancoderSim from hardware_interface.drivetrain import getAxleRadians, getWheelRadians, SwerveModule, AXLE_JOINT_GEAR_RATIO from hardware_interface.armcontroller import PORTS, TOTAL_INTAKE_REVOLUTIONS from hardware_interface.joystick import CONTROLLER_PORT import math import typing if typing.TYPE_CHECKING: from robot import EdnaRobot # Calculations axle_radius = 0.05 axle_mass = 0.23739 wheel_radius = 0.0508 wheel_length = 0.0381 wheel_mass = 0.2313 center_axle_moi = 0.5 * pow(axle_radius, 2) * axle_mass center_side_wheel_moi = (0.25 * pow(wheel_radius, 2) * wheel_mass) + ((1/12) * pow(wheel_length, 2) * wheel_mass) center_wheel_moi = 0.5 * pow(wheel_radius, 2) * wheel_mass class PhysicsEngine: def __init__(self, physics_controller: PhysicsInterface, robot: "EdnaRobot"): self.physics_controller = physics_controller self.xbox = wpilib.simulation.XboxControllerSim(CONTROLLER_PORT) self.roborio = wpilib.simulation.RoboRioSim() self.battery = wpilib.simulation.BatterySim() self.roborio.setVInVoltage(self.battery.calculate([0.0])) self.frontLeftModuleSim = SwerveModuleSim(robot.drive_train.front_left) self.frontRightModuleSim = SwerveModuleSim(robot.drive_train.front_right) self.rearLeftModuleSim = SwerveModuleSim(robot.drive_train.rear_left) self.rearRightModuleSim = SwerveModuleSim(robot.drive_train.rear_right) self.elevator = TalonFxSim(robot.arm_controller.elevator.motor, 0.0003, 1, False) # self.intake = TalonFxSim(robot.arm_controller.bottom_gripper_lift.motor, 0.0004, 1, False) # self.intake.addLimitSwitch("fwd", 0) # self.intake.addLimitSwitch("rev", TOTAL_INTAKE_REVOLUTIONS * -2 * math.pi) self.pneumaticHub = wpilib.simulation.REVPHSim(PORTS['HUB']) self.armRollerBar = wpilib.simulation.DoubleSolenoidSim(self.pneumaticHub, *PORTS['ARM_ROLLER_BAR']) self.topGripperSlider = wpilib.simulation.DoubleSolenoidSim(self.pneumaticHub, *PORTS['TOP_GRIPPER_SLIDER']) self.topGripper = wpilib.simulation.DoubleSolenoidSim(self.pneumaticHub, *PORTS['TOP_GRIPPER']) def update_sim(self, now: float, tm_diff: float) -> None: # Simulate Swerve Modules self.frontLeftModuleSim.update(tm_diff) self.frontRightModuleSim.update(tm_diff) self.rearLeftModuleSim.update(tm_diff) self.rearRightModuleSim.update(tm_diff) # Simulate Arm self.elevator.update(tm_diff) # self.intake.update(tm_diff) # Add Currents into Battery Simulation self.roborio.setVInVoltage(self.battery.calculate([0.0])) class SwerveModuleSim(): wheel : TalonFxSim = None axle : TalonFxSim = None encoder : CancoderSim = None def __init__(self, module: "SwerveModule"): wheelMOI = center_wheel_moi axleMOI = center_axle_moi + center_side_wheel_moi self.wheel = TalonFxSim(module.wheel_motor, wheelMOI, 1, False) self.axle = TalonFxSim(module.axle_motor, axleMOI, AXLE_JOINT_GEAR_RATIO, False) self.encoder = CancoderSim(module.encoder, module.encoder_offset, True) # There is a bad feedback loop between controller and the rio code # It will create oscillations in the simulation when the robot is not being commanded to move # The issue is from the controller commanding the axle position to stay at the same position when idle # but if the axle is moving during that time it will constantly overshoot the idle position def update(self, tm_diff): self.wheel.update(tm_diff) self.axle.update(tm_diff) self.encoder.update(tm_diff, self.axle.getVelocityRadians()) # Useful for debugging the simulation or code def __str__(self) -> str: wheelPos = getWheelRadians(self.wheel.talon.getSelectedSensorPosition(), "position") wheelVel = getWheelRadians(self.wheel.talon.getSelectedSensorVelocity(), "velocity") stateStr = f"Wheel POS: {wheelPos:5.2f} VEL: {wheelVel:5.2f} " axlePos = getAxleRadians(self.axle.talon.getSelectedSensorPosition(), "position") axleVel = getAxleRadians(self.axle.talon.getSelectedSensorVelocity(), "velocity") stateStr += f"Axle POS: {axlePos:5.2f} VEL: {axleVel:5.2f} " encoderPos = math.radians(self.encoder.cancoder.getAbsolutePosition()) encoderVel = math.radians(self.encoder.cancoder.getVelocity()) stateStr += f"Encoder POS: {encoderPos:5.2f} VEL: {encoderVel:5.2f}" return stateStr
4,791
Python
43.785046
116
0.707577
RoboEagles4828/edna2023/rio/README.md
# RIO Code
10
Markdown
9.99999
10
0.7
RoboEagles4828/edna2023/rio/dds/dds.py
import rticonnextdds_connector as rti import logging # Subscribe to DDS topics class DDS_Subscriber: def __init__(self, xml_path, participant_name, reader_name): # Connectors are not thread safe, so we need to create a new one for each thread self.connector = rti.Connector(config_name=participant_name, url=xml_path) self.input = self.connector.get_input(reader_name) def read(self) -> dict: # Take the input data off of queue and read it try: self.input.take() except rti.Error as e: logging.warn("RTI Read Error", e.args) # Return the first valid data sample data = None for sample in self.input.samples.valid_data_iter: data = sample.get_dictionary() break return data def close(self): self.connector.close() # Publish to DDS topics class DDS_Publisher: def __init__(self, xml_path, participant_name, writer_name): self.connector = rti.Connector(config_name=participant_name, url=xml_path) self.output = self.connector.get_output(writer_name) def write(self, data) -> None: if data: self.output.instance.set_dictionary(data) try: self.output.write() except rti.Error as e: logging.warn("RTI Write Error", e.args) # else: # logging.warn("No data to write") def close(self): self.connector.close()
1,491
Python
31.434782
88
0.608987
RoboEagles4828/edna2023/rio/sim/cancoderSim.py
from ctre.sensors import CANCoder, CANCoderSimCollection import math CANCODER_TICKS_PER_REV = 4096 class CancoderSim(): def __init__(self, cancoder : CANCoder, offsetDegress : float = 0.0, sensorPhase: bool = False): self.cancoder : CANCoder = cancoder self.cancoderSim : CANCoderSimCollection = self.cancoder.getSimCollection() self.cancoderSim.setRawPosition(self.radiansToEncoderTicks(0, "position")) self.offset = math.radians(offsetDegress) self.sensorPhase = -1 if sensorPhase else 1 self.velocity = 0.0 self.position = 0.0 def update(self, period : float, velocityRadians : float): self.position = velocityRadians * period * self.sensorPhase self.velocity = velocityRadians * self.sensorPhase # Update the encoder sensors on the motor self.cancoderSim = self.cancoder.getSimCollection() self.cancoderSim.addPosition(self.radiansToEncoderTicks(self.position, "position")) self.cancoderSim.setVelocity(self.radiansToEncoderTicks(self.velocity, "velocity")) def radiansToEncoderTicks(self, radians : float, displacementType : str) -> int: ticks = radians * CANCODER_TICKS_PER_REV / (2 * math.pi) if displacementType == "position": return int(ticks) else: return int(ticks / 10)
1,367
Python
43.129031
100
0.67959
RoboEagles4828/edna2023/rio/sim/talonFxSim.py
from ctre import TalonFX, TalonFXSimCollection from wpilib import RobotController import random import math from pyfrc.physics.motor_cfgs import MOTOR_CFG_FALCON_500 import wpilib.simulation import wpimath.system.plant FALCON_SENSOR_TICKS_PER_REV = 2048 class TalonFxSim: def __init__(self, talonFx : TalonFX, moi : float, gearRatio : float, sensorPhase : bool ) -> None: self.talon : TalonFX = talonFx self.talonSim : TalonFXSimCollection = None self.moi = moi self.gearRatio = gearRatio self.sensorPhase = -1 if sensorPhase else 1 self.gearbox = wpimath.system.plant.DCMotor.falcon500(1) self.motor = wpilib.simulation.DCMotorSim(self.gearbox, self.gearRatio, self.moi, [0.0, 0.0]) self.velocity = 0.0 self.position = 0.0 self.fwdLimitEnabled = False self.fwdLimit = 0.0 self.revLimitEnabled = False self.revLimit = 0.0 # Simulates the movement of falcon 500 motors by getting the voltages from the # the motor model that is being controlled by the robot code. def update(self, period : float): self.talonSim = self.talon.getSimCollection() # Update the motor model voltage = self.talonSim.getMotorOutputLeadVoltage() * self.sensorPhase self.motor.setInputVoltage(voltage) self.motor.update(period) newPosition = self.motor.getAngularPosition() self.deltaPosition = newPosition - self.position self.position = newPosition self.velocity = self.motor.getAngularVelocity() if self.fwdLimitEnabled and self.position >= self.fwdLimit: self.talonSim.setLimitFwd(True) self.position = self.fwdLimit else: self.talonSim.setLimitFwd(False) if self.revLimitEnabled and self.position <= self.revLimit: self.talonSim.setLimitRev(True) self.position = self.revLimit else: self.talonSim.setLimitRev(False) # Update the encoder sensors on the motor positionShaftTicks = int(self.radiansToSensorTicks(self.position * self.gearRatio, "position")) velocityShaftTicks = int(self.radiansToSensorTicks(self.velocity * self.gearRatio, "velocity")) self.talonSim.setIntegratedSensorRawPosition(positionShaftTicks) self.talonSim.setIntegratedSensorVelocity(velocityShaftTicks) # Update the current and voltage self.talonSim.setSupplyCurrent(self.motor.getCurrentDraw()) self.talonSim.setBusVoltage(RobotController.getBatteryVoltage()) def radiansToSensorTicks(self, radians : float, displacementType : str) -> int: ticks = radians * FALCON_SENSOR_TICKS_PER_REV / (2 * math.pi) if displacementType == "position": return ticks else: return ticks / 10 def getPositionRadians(self) -> float: return self.position def getVelocityRadians(self) -> float: return self.velocity def getSupplyCurrent(self) -> float: return self.motor.getCurrentDraw() def addLimitSwitch(self, limitType: str, positionRadians: float): if limitType == "fwd": self.fwdLimitEnabled = True self.fwdLimit = positionRadians elif limitType == "rev": self.revLimitEnabled = True self.revLimit = positionRadians else: print("Invalid limit type")
3,473
Python
38.033707
103
0.663403
RoboEagles4828/edna2023/rio/hardware_interface/armcontroller.py
import wpilib import wpilib.simulation import ctre import ctre.sensors import time import logging import math NAMESPACE = 'real' CMD_TIMEOUT_SECONDS = 1 MOTOR_TIMEOUT = 30 # 0 means do not use the timeout TICKS_PER_REVOLUTION = 2048.0 TOTAL_ELEVATOR_REVOLUTIONS = 164 TOTAL_INTAKE_REVOLUTIONS = 6 SCALING_FACTOR_FIX = 10000 # Port Numbers for all of the Solenoids and other connected things # The numbers below will **need** to be changed to fit the robot wiring PORTS = { # Modules 'HUB': 18, # Pistons 'ARM_ROLLER_BAR': [14, 15], 'TOP_GRIPPER_SLIDER': [10, 11], 'TOP_GRIPPER': [12, 13], # Wheels 'ELEVATOR': 13, # 'BOTTOM_GRIPPER_LIFT': 14 } MOTOR_PID_CONFIG = { 'SLOT': 2, 'MAX_SPEED': 18000, # Ticks/100ms 'TARGET_ACCELERATION': 14000, # Ticks/100ms "kP": 0.2, "kI": 0.0, "kD": 0.1, "kF": 0.2, } JOINT_LIST = [ 'arm_roller_bar_joint', 'top_slider_joint', 'top_gripper_left_arm_joint', 'elevator_center_joint', ] def getJointList(): return JOINT_LIST class ArmController(): def __init__(self): self.last_cmds_time = time.time() self.warn_timeout = True self.hub = wpilib.PneumaticHub(PORTS['HUB']) self.compressor = self.hub.makeCompressor() self.arm_roller_bar = Piston(self.hub, PORTS['ARM_ROLLER_BAR'], max=0.07, name="Arm Roller Bar") self.top_gripper_slider = Piston(self.hub, PORTS['TOP_GRIPPER_SLIDER'], max=0.30, name="Top Gripper Slider") self.top_gripper = Piston(self.hub, PORTS['TOP_GRIPPER'], min=0.0, max=-0.9, name="Top Gripper", reverse=True) self.elevator = Elevator(PORTS['ELEVATOR'], max=0.56) self.JOINT_MAP = { # Pneumatics 'arm_roller_bar_joint': self.arm_roller_bar, 'top_slider_joint': self.top_gripper_slider, 'top_gripper_left_arm_joint': self.top_gripper, # Wheels 'elevator_center_joint': self.elevator, } def getEncoderData(self): names = [""]*4 positions = [0]*4 velocities = [0]*4 # Iterate over the JOINT_MAP and run the get() function for each of them for index, joint_name in enumerate(self.JOINT_MAP): names[index] = joint_name # Allow for joints to be removed quickly positions[index] = int(self.JOINT_MAP[joint_name].getPosition() * SCALING_FACTOR_FIX) velocities[index] = int(self.JOINT_MAP[joint_name].getVelocity() * SCALING_FACTOR_FIX) return { "name" : names, "position": positions, "velocity": velocities} def stop(self): for joint in self.JOINT_MAP.values(): joint.stop() def sendCommands(self, commands): if commands: self.last_cmds_time = time.time() self.warn_timeout = True for i in range(len(commands["name"])): joint_name = commands["name"][i] if joint_name in self.JOINT_MAP: self.JOINT_MAP[joint_name].setPosition(commands['position'][i]) elif (time.time() - self.last_cmds_time > CMD_TIMEOUT_SECONDS): self.stop() if self.warn_timeout: logging.warning(f"Didn't recieve any commands for {CMD_TIMEOUT_SECONDS} second(s). Halting...") self.warn_timeout = False class Piston(): def __init__(self, hub : wpilib.PneumaticHub, ports : list[int], min : float = 0.0, max : float = 1.0, reverse : bool = False, name : str = "Piston"): self.solenoid = hub.makeDoubleSolenoid(ports[0], ports[1]) self.state = self.solenoid.get() != wpilib.DoubleSolenoid.Value.kForward self.min = min self.max = max self.reverse = reverse self.name = name self.lastCommand = None def getPosition(self): return float(self.state) * (self.max - self.min) + self.min # The Solenoids don't have a velocity value, so we set it to zero here def getVelocity(self): return 0.0 def stop(self): self.solenoid.set(wpilib.DoubleSolenoid.Value.kOff) def setPosition(self, position : float): if position != self.lastCommand: logging.info(f"{self.name} Position: {position}") self.lastCommand = position center = abs((self.max - self.min) / 2 + self.min) forward = wpilib.DoubleSolenoid.Value.kForward reverse = wpilib.DoubleSolenoid.Value.kReverse if abs(position) >= center and self.state == 0: logging.info(f"{self.name} first block") self.solenoid.set(reverse if self.reverse else forward) self.state = 1 elif abs(position) < center and self.state == 1: logging.info(f"{self.name} first block") self.solenoid.set(forward if self.reverse else reverse) self.state = 0 def commonTalonSetup(talon : ctre.WPI_TalonFX): talon.configFactoryDefault(MOTOR_TIMEOUT) talon.configNeutralDeadband(0.01, MOTOR_TIMEOUT) # Voltage talon.configVoltageCompSaturation(12, MOTOR_TIMEOUT) talon.enableVoltageCompensation(True) # Sensor talon.configSelectedFeedbackSensor(ctre.FeedbackDevice.IntegratedSensor, 0, MOTOR_TIMEOUT) talon.configIntegratedSensorInitializationStrategy(ctre.sensors.SensorInitializationStrategy.BootToZero) # PID talon.selectProfileSlot(MOTOR_PID_CONFIG['SLOT'], 0) talon.config_kP(MOTOR_PID_CONFIG['SLOT'], MOTOR_PID_CONFIG['kP'], MOTOR_TIMEOUT) talon.config_kI(MOTOR_PID_CONFIG['SLOT'], MOTOR_PID_CONFIG['kI'], MOTOR_TIMEOUT) talon.config_kD(MOTOR_PID_CONFIG['SLOT'], MOTOR_PID_CONFIG['kD'], MOTOR_TIMEOUT) talon.config_kD(MOTOR_PID_CONFIG['SLOT'], MOTOR_PID_CONFIG['kF'], MOTOR_TIMEOUT) # Nominal and Peak talon.configNominalOutputForward(0, MOTOR_TIMEOUT) talon.configNominalOutputReverse(0, MOTOR_TIMEOUT) talon.configPeakOutputForward(1, MOTOR_TIMEOUT) talon.configPeakOutputReverse(-1, MOTOR_TIMEOUT) return class Intake(): def __init__(self, port : int, min : float = 0.0, max : float = 1.0): self.motor = ctre.WPI_TalonFX(port, "rio") commonTalonSetup(self.motor) self.state = 0 self.min = min self.max = max self.totalTicks = TICKS_PER_REVOLUTION * TOTAL_INTAKE_REVOLUTIONS self.lastCommand = None # Phase self.motor.setSensorPhase(False) self.motor.setInverted(False) # Frames self.motor.setStatusFramePeriod(ctre.StatusFrameEnhanced.Status_13_Base_PIDF0, 10, MOTOR_TIMEOUT) # Brake self.motor.setNeutralMode(ctre.NeutralMode.Brake) def getPosition(self): percent = self.motor.getSelectedSensorPosition() / self.totalTicks return percent * (self.max - self.min) + self.min def getVelocity(self): percent = self.motor.getSelectedSensorVelocity() * 10 / self.totalTicks return percent * (self.max - self.min) + self.min def stop(self): self.motor.set(ctre.TalonFXControlMode.PercentOutput, 0) def setPosition(self, position : float): if position != self.lastCommand: logging.info(f"Intake Position: {position}") self.lastCommand = position # Moves the intake center = (self.max - self.min) / 2 + self.min if position >= center and self.state == 0: self.motor.set(ctre.TalonFXControlMode.Velocity, -TICKS_PER_REVOLUTION/2) self.state = 1 elif position < center and self.state == 1: self.motor.set(ctre.TalonFXControlMode.Velocity, TICKS_PER_REVOLUTION/2) self.state = 0 if self.state == 0 and not self.motor.isFwdLimitSwitchClosed(): self.motor.set(ctre.TalonFXControlMode.Velocity, TICKS_PER_REVOLUTION/2) elif self.state == 1 and not self.motor.isRevLimitSwitchClosed(): self.motor.set(ctre.TalonFXControlMode.Velocity, -TICKS_PER_REVOLUTION/2) class Elevator(): def __init__(self, port : int, min : float = 0.0, max : float = 1.0): self.motor = ctre.WPI_TalonFX(port, "rio") commonTalonSetup(self.motor) self.min = min self.max = max self.totalTicks = TICKS_PER_REVOLUTION * TOTAL_ELEVATOR_REVOLUTIONS self.lastCommand = None # Phase self.motor.setSensorPhase(False) self.motor.setInverted(False) # Frames self.motor.setStatusFramePeriod(ctre.StatusFrameEnhanced.Status_10_MotionMagic, 10, MOTOR_TIMEOUT) # Motion Magic self.motor.configMotionCruiseVelocity(MOTOR_PID_CONFIG['MAX_SPEED'], MOTOR_TIMEOUT) # Sets the maximum speed of motion magic (ticks/100ms) self.motor.configMotionAcceleration(MOTOR_PID_CONFIG['TARGET_ACCELERATION'], MOTOR_TIMEOUT) # Sets the maximum acceleration of motion magic (ticks/100ms) # self.motor.configClearPositionOnLimitR(True) def getPosition(self) -> float: percent = self.motor.getSelectedSensorPosition() / self.totalTicks return percent * (self.max - self.min) + self.min def getVelocity(self) -> float: percent = (self.motor.getSelectedSensorVelocity() * 10) / self.totalTicks return percent * (self.max - self.min) + self.min def stop(self): self.motor.set(ctre.TalonFXControlMode.PercentOutput, 0) def setPosition(self, position : float): if position != self.lastCommand: logging.info(f"Elevator Position: {position}") self.lastCommand = position percent = (position - self.min) / (self.max - self.min) self.motor.set(ctre.TalonFXControlMode.MotionMagic, percent * self.totalTicks)
9,753
Python
38.016
161
0.63724
RoboEagles4828/edna2023/rio/hardware_interface/joystick.py
import wpilib import logging CONTROLLER_PORT = 0 SCALING_FACTOR_FIX = 10000 ENABLE_THROTTLE = True pov_x_map = { -1: 0.0, 0: 0.0, 45: -1.0, 90: -1.0, 135: -1.0, 180: 0.0, 225: 1.0, 270: 1.0, 315: 1.0, } pov_y_map = { -1: 0.0, 0: 1.0, 45: 1.0, 90: 0.0, 135: -1.0, 180: -1.0, 225: -1.0, 270: 0.0, 315: 1.0, } class Joystick: def __init__(self): self.joystick = wpilib.XboxController(CONTROLLER_PORT) self.deadzone = 0.15 self.last_joystick_data = self.getEmptyData() self.count = 0 def scaleAxis(self, axis): return int(axis * SCALING_FACTOR_FIX * -1) def scaleTrigger(self, trigger): return int(trigger * SCALING_FACTOR_FIX * -1) def getEmptyData(self): return { "axes": [0.0] * 8, "buttons": [0] * 11, } def getData(self): pov = self.joystick.getPOV(0) leftX = self.joystick.getLeftX() leftY = self.joystick.getLeftY() rightX = self.joystick.getRightX() rightY = self.joystick.getRightY() leftTrigger = self.joystick.getLeftTriggerAxis() rightTrigger = self.joystick.getRightTriggerAxis() axes = [ self.scaleAxis(leftX) if abs(leftX) > self.deadzone else 0.0, self.scaleAxis(leftY) if abs(leftY) > self.deadzone else 0.0, self.scaleTrigger(leftTrigger), self.scaleAxis(rightX) if abs(rightX) > self.deadzone else 0.0, self.scaleAxis(rightY) if abs(rightY) > self.deadzone else 0.0, self.scaleTrigger(rightTrigger), pov_x_map[pov], # left 1.0 right -1.0 pov_y_map[pov], # up 1.0 down -1.0 ] buttons = [ int(self.joystick.getAButton()), int(self.joystick.getBButton()), int(self.joystick.getXButton()), int(self.joystick.getYButton()), int(self.joystick.getLeftBumper()), int(self.joystick.getRightBumper()), int(self.joystick.getBackButton()), int(self.joystick.getStartButton()), 0, int(self.joystick.getLeftStickButton()), int(self.joystick.getRightStickButton()) ] data = {"axes": axes, "buttons": buttons} if ENABLE_THROTTLE: if self.is_equal(data, self.last_joystick_data): self.count += 1 if self.count >= 10: return None else: self.count = 0 self.last_joystick_data = data return data else: return data def is_equal(self, d, d1): res = all((d1.get(k) == v for k, v in d.items())) return res
2,835
Python
25.504673
75
0.522751
RoboEagles4828/edna2023/rio/hardware_interface/drivetrain.py
import wpilib import ctre import ctre.sensors import math import time import logging from wpimath.filter import SlewRateLimiter NAMESPACE = 'real' # Small Gear Should Face the back of the robot # All wheel drive motors should not be inverted # All axle turn motors should be inverted + sensor phase # All Cancoders should be direction false MODULE_CONFIG = { "front_left": { "wheel_joint_name": "front_left_wheel_joint", "wheel_motor_port": 3, #9 "axle_joint_name": "front_left_axle_joint", "axle_motor_port": 1, #7 "axle_encoder_port": 2, #8 "encoder_offset": 18.984 # 248.203, }, "front_right": { "wheel_joint_name": "front_right_wheel_joint", "wheel_motor_port": 6, #12 "axle_joint_name": "front_right_axle_joint", "axle_motor_port": 4, #10 "axle_encoder_port": 5, #11 "encoder_offset": 145.723 #15.908, }, "rear_left": { "wheel_joint_name": "rear_left_wheel_joint", "wheel_motor_port": 12, #6 "axle_joint_name": "rear_left_axle_joint", "axle_motor_port": 10, #4 "axle_encoder_port": 11, #5 "encoder_offset": 194.678 #327.393, }, "rear_right": { "wheel_joint_name": "rear_right_wheel_joint", "wheel_motor_port": 9, #3 "axle_joint_name": "rear_right_axle_joint", "axle_motor_port": 7, #1 "axle_encoder_port": 8, #2 "encoder_offset": 69.785 #201.094, } } def getJointList(): joint_list = [] for module in MODULE_CONFIG.values(): joint_list.append(module['wheel_joint_name']) joint_list.append(module['axle_joint_name']) return joint_list AXLE_DIRECTION = False WHEEL_DIRECTION = False ENCODER_DIRECTION = True WHEEL_JOINT_GEAR_RATIO = 6.75 #8.14 AXLE_JOINT_GEAR_RATIO = 150.0/7.0 TICKS_PER_REV = 2048.0 CMD_TIMEOUT_SECONDS = 1 nominal_voltage = 9.0 steer_current_limit = 20.0 # This is needed to fix bad float values being published by RTI from the RIO. # To fix this, we scale the float and convert to integers. # Then we scale it back down inside the ROS2 hardware interface. SCALING_FACTOR_FIX = 10000 # Encoder Constants encoder_ticks_per_rev = 4096.0 encoder_reset_velocity = math.radians(0.5) encoder_reset_iterations = 500 axle_pid_constants = { "kP": 0.2, "kI": 0.0, "kD": 0.1, "kF": 0.2, "kIzone": 0, "kPeakOutput": 1.0 } wheel_pid_constants = { "kF": 1023.0/20660.0, "kP": 0.1, "kI": 0.001, "kD": 5 } slot_idx = 0 pid_loop_idx = 0 timeout_ms = 30 velocityConstant = 0.5 accelerationConstant = 0.25 # Conversion Functions positionCoefficient = 2.0 * math.pi / TICKS_PER_REV / AXLE_JOINT_GEAR_RATIO velocityCoefficient = positionCoefficient * 10.0 # axle (radians) -> shaft (ticks) def getShaftTicks(radians, displacementType) -> int: if displacementType == "position": return int(radians / positionCoefficient) elif displacementType == "velocity": return int(radians / velocityCoefficient) else: return 0 # shaft (ticks) -> axle (radians) def getAxleRadians(ticks, displacementType): if displacementType == "position": return ticks * positionCoefficient elif displacementType == "velocity": return ticks * velocityCoefficient else: return 0 wheelPositionCoefficient = 2.0 * math.pi / TICKS_PER_REV / WHEEL_JOINT_GEAR_RATIO wheelVelocityCoefficient = wheelPositionCoefficient * 10.0 # wheel (radians) -> shaft (ticks) def getWheelShaftTicks(radians, displacementType) -> int: if displacementType == "position": return int(radians / wheelPositionCoefficient) elif displacementType == "velocity": return int(radians / wheelVelocityCoefficient) else: return 0 # shaft (ticks) -> wheel (radians) def getWheelRadians(ticks, displacementType): if displacementType == "position": return ticks * wheelPositionCoefficient elif displacementType == "velocity": return ticks * wheelVelocityCoefficient else: return 0 class SwerveModule(): def __init__(self, module_config) -> None: #IMPORTANT: # The wheel joint is the motor that drives the wheel. # The axle joint is the motor that steers the wheel. self.wheel_joint_name = module_config["wheel_joint_name"] self.axle_joint_name = module_config["axle_joint_name"] self.wheel_joint_port = module_config["wheel_motor_port"] self.axle_joint_port = module_config["axle_motor_port"] self.axle_encoder_port = module_config["axle_encoder_port"] self.encoder_offset = module_config["encoder_offset"] self.wheel_motor = ctre.WPI_TalonFX(self.wheel_joint_port, "rio") self.axle_motor = ctre.WPI_TalonFX(self.axle_joint_port, "rio") self.encoder = ctre.sensors.WPI_CANCoder(self.axle_encoder_port, "rio") self.last_wheel_vel_cmd = None self.last_axle_vel_cmd = None self.reset_iterations = 0 self.setupEncoder() self.setupWheelMotor() self.setupAxleMotor() def setupEncoder(self): self.encoderconfig = ctre.sensors.CANCoderConfiguration() self.encoderconfig.absoluteSensorRange = ctre.sensors.AbsoluteSensorRange.Unsigned_0_to_360 self.encoderconfig.initializationStrategy = ctre.sensors.SensorInitializationStrategy.BootToAbsolutePosition self.encoderconfig.sensorDirection = ENCODER_DIRECTION self.encoder.configAllSettings(self.encoderconfig) self.encoder.setPositionToAbsolute(timeout_ms) self.encoder.setStatusFramePeriod(ctre.sensors.CANCoderStatusFrame.SensorData, 10, timeout_ms) def getEncoderPosition(self): return math.radians(self.encoder.getAbsolutePosition() - self.encoder_offset) def getEncoderVelocity(self): return math.radians(self.encoder.getVelocity()) def setupWheelMotor(self): self.wheel_motor.configFactoryDefault() self.wheel_motor.configNeutralDeadband(0.01, timeout_ms) # Direction and Sensors self.wheel_motor.setSensorPhase(WHEEL_DIRECTION) self.wheel_motor.setInverted(WHEEL_DIRECTION) self.wheel_motor.configSelectedFeedbackSensor(ctre.FeedbackDevice.IntegratedSensor, slot_idx, timeout_ms) self.wheel_motor.setStatusFramePeriod(ctre.StatusFrameEnhanced.Status_21_FeedbackIntegrated, 10, timeout_ms) # Peak and Nominal Outputs self.wheel_motor.configNominalOutputForward(0, timeout_ms) self.wheel_motor.configNominalOutputReverse(0, timeout_ms) self.wheel_motor.configPeakOutputForward(1, timeout_ms) self.wheel_motor.configPeakOutputReverse(-1, timeout_ms) # Voltage Comp self.wheel_motor.configVoltageCompSaturation(nominal_voltage, timeout_ms) self.axle_motor.enableVoltageCompensation(True) # Tuning self.wheel_motor.config_kF(0, wheel_pid_constants["kF"], timeout_ms) self.wheel_motor.config_kP(0, wheel_pid_constants["kP"], timeout_ms) self.wheel_motor.config_kI(0, wheel_pid_constants["kI"], timeout_ms) self.wheel_motor.config_kD(0, wheel_pid_constants["kD"], timeout_ms) # Brake self.wheel_motor.setNeutralMode(ctre.NeutralMode.Brake) # Velocity Ramp # TODO: Tweak this value self.wheel_motor.configClosedloopRamp(0.1) # Current Limit current_limit = 20 current_threshold = 40 current_threshold_time = 0.1 supply_current_limit_configs = ctre.SupplyCurrentLimitConfiguration(True, current_limit, current_threshold, current_threshold_time) self.wheel_motor.configSupplyCurrentLimit(supply_current_limit_configs, timeout_ms) def setupAxleMotor(self): self.axle_motor.configFactoryDefault() self.axle_motor.configNeutralDeadband(0.01, timeout_ms) # Direction and Sensors self.axle_motor.setSensorPhase(AXLE_DIRECTION) self.axle_motor.setInverted(AXLE_DIRECTION) self.axle_motor.configSelectedFeedbackSensor(ctre.FeedbackDevice.IntegratedSensor, slot_idx, timeout_ms) # self.axle_motor.setStatusFramePeriod(ctre.StatusFrameEnhanced.Status_13_Base_PIDF0, 10, timeout_ms) self.axle_motor.setStatusFramePeriod(ctre.StatusFrameEnhanced.Status_10_MotionMagic, 10, timeout_ms) self.axle_motor.setSelectedSensorPosition(getShaftTicks(self.getEncoderPosition(), "position"), pid_loop_idx, timeout_ms) # Peak and Nominal Outputs self.axle_motor.configNominalOutputForward(0, timeout_ms) self.axle_motor.configNominalOutputReverse(0, timeout_ms) self.axle_motor.configPeakOutputForward(1, timeout_ms) self.axle_motor.configPeakOutputReverse(-1, timeout_ms) # Tuning self.axle_motor.selectProfileSlot(slot_idx, pid_loop_idx) self.axle_motor.config_kP(slot_idx, axle_pid_constants["kP"], timeout_ms) self.axle_motor.config_kI(slot_idx, axle_pid_constants["kI"], timeout_ms) self.axle_motor.config_kD(slot_idx, axle_pid_constants["kD"], timeout_ms) self.axle_motor.config_kF(slot_idx, (1023.0 * velocityCoefficient / nominal_voltage) * velocityConstant, timeout_ms) self.axle_motor.configMotionCruiseVelocity(2.0 / velocityConstant / velocityCoefficient, timeout_ms) self.axle_motor.configMotionAcceleration((8.0 - 2.0) / accelerationConstant / velocityCoefficient, timeout_ms) self.axle_motor.configMotionSCurveStrength(2) # Voltage Comp self.axle_motor.configVoltageCompSaturation(nominal_voltage, timeout_ms) self.axle_motor.enableVoltageCompensation(True) # Braking self.axle_motor.setNeutralMode(ctre.NeutralMode.Brake) def neutralize_module(self): self.wheel_motor.set(ctre.TalonFXControlMode.PercentOutput, 0) self.axle_motor.set(ctre.TalonFXControlMode.PercentOutput, 0) def set(self, wheel_motor_vel, axle_position): wheel_vel = getWheelShaftTicks(wheel_motor_vel, "velocity") if abs(wheel_motor_vel) < 0.2: self.neutralize_module() return else: self.wheel_motor.set(ctre.TalonFXControlMode.Velocity, wheel_vel) self.last_wheel_vel_cmd = wheel_vel # MOTION MAGIC CONTROL FOR AXLE POSITION axle_motorPosition = getAxleRadians(self.axle_motor.getSelectedSensorPosition(), "position") axle_motorVelocity = getAxleRadians(self.axle_motor.getSelectedSensorVelocity(), "velocity") axle_absolutePosition = self.getEncoderPosition() # Reset if axle_motorVelocity < encoder_reset_velocity: self.reset_iterations += 1 if self.reset_iterations >= encoder_reset_iterations: self.reset_iterations = 0 self.axle_motor.setSelectedSensorPosition(getShaftTicks(axle_absolutePosition, "position")) axle_motorPosition = axle_absolutePosition else: self.reset_iterations = 0 # First let's assume that we will move directly to the target position. newAxlePosition = axle_position # The motor could get to the target position by moving clockwise or counterclockwise. # The shortest path should be the direction that is less than pi radians away from the current motor position. # The shortest path could loop around the circle and be less than 0 or greater than 2pi. # We need to get the absolute current position to determine if we need to loop around the 0 - 2pi range. # The current motor position does not stay inside the 0 - 2pi range. # We need the absolute position to compare with the target position. axle_absoluteMotorPosition = math.fmod(axle_motorPosition, 2.0 * math.pi) if axle_absoluteMotorPosition < 0.0: axle_absoluteMotorPosition += 2.0 * math.pi # If the target position was in the first quadrant area # and absolute motor position was in the last quadrant area # then we need to move into the next loop around the circle. if newAxlePosition - axle_absoluteMotorPosition < -math.pi: newAxlePosition += 2.0 * math.pi # If the target position was in the last quadrant area # and absolute motor position was in the first quadrant area # then we need to move into the previous loop around the circle. elif newAxlePosition - axle_absoluteMotorPosition > math.pi: newAxlePosition -= 2.0 * math.pi # Last, add the current existing loops that the motor has gone through. newAxlePosition += axle_motorPosition - axle_absoluteMotorPosition self.axle_motor.set(ctre.TalonFXControlMode.MotionMagic, getShaftTicks(newAxlePosition, "position")) # logging.info('AXLE MOTOR POS: ', newAxlePosition) # logging.info('WHEEL MOTOR VEL: ', wheel_vel) def stop(self): self.wheel_motor.set(ctre.TalonFXControlMode.PercentOutput, 0) self.axle_motor.set(ctre.TalonFXControlMode.PercentOutput, 0) def getEncoderData(self): output = [ { "name": self.wheel_joint_name, "position": int(getWheelRadians(self.wheel_motor.getSelectedSensorPosition(), "position") * SCALING_FACTOR_FIX), "velocity": int(getWheelRadians(self.wheel_motor.getSelectedSensorVelocity(), "velocity") * SCALING_FACTOR_FIX) }, { "name": self.axle_joint_name, "position": int(self.getEncoderPosition() * SCALING_FACTOR_FIX), "velocity": int(self.getEncoderVelocity() * SCALING_FACTOR_FIX) } ] return output class DriveTrain(): def __init__(self): self.last_cmds = { "name" : getJointList(), "position": [0.0]*len(getJointList()), "velocity": [0.0]*len(getJointList()) } self.last_cmds_time = time.time() self.warn_timeout = True self.front_left = SwerveModule(MODULE_CONFIG["front_left"]) self.front_right = SwerveModule(MODULE_CONFIG["front_right"]) self.rear_left = SwerveModule(MODULE_CONFIG["rear_left"]) self.rear_right = SwerveModule(MODULE_CONFIG["rear_right"]) self.module_lookup = \ { 'front_left_axle_joint': self.front_left, 'front_right_axle_joint': self.front_right, 'rear_left_axle_joint': self.rear_left, 'rear_right_axle_joint': self.rear_right, } def getEncoderData(self): names = [""]*8 positions = [0]*8 velocities = [0]*8 encoderInfo = [] encoderInfo += self.front_left.getEncoderData() encoderInfo += self.front_right.getEncoderData() encoderInfo += self.rear_left.getEncoderData() encoderInfo += self.rear_right.getEncoderData() assert len(encoderInfo) == 8 for index, encoder in enumerate(encoderInfo): names[index] = encoder['name'] positions[index] = encoder['position'] velocities[index] = encoder['velocity'] return { "name": names, "position": positions, "velocity": velocities } def stop(self): self.front_left.stop() self.front_right.stop() self.rear_left.stop() self.rear_right.stop() def sendCommands(self, commands): if commands: self.last_cmds = commands self.last_cmds_time = time.time() self.warn_timeout = True for i in range(len(commands['name'])): if 'axle' in commands['name'][i]: axle_name = commands['name'][i] axle_position = commands['position'][i] if len(commands['position']) > i else 0.0 wheel_name = axle_name.replace('axle', 'wheel') wheel_index = commands['name'].index(wheel_name) wheel_velocity = commands['velocity'][wheel_index] if len(commands['velocity']) > wheel_index else 0.0 module = self.module_lookup[axle_name] module.set(wheel_velocity, axle_position) if axle_name == "front_left_axle_joint": # logging.info(f"{wheel_name}: {wheel_velocity}\n{axle_name}: {axle_position}") pass else: current_time = time.time() if current_time - self.last_cmds_time > CMD_TIMEOUT_SECONDS: self.stop() # Display Warning Once if self.warn_timeout: logging.warning("CMD TIMEOUT: HALTING") self.warn_timeout = False
16,813
Python
40.413793
139
0.650984
RoboEagles4828/edna2023/rio/POC/pneumatics_test/robot.py
import wpilib # does not work yet class MyRobot(wpilib.TimedRobot): def robotInit(self): print("Initalizing") # make rev hub object self.hub = wpilib.PneumaticHub(1) # make single solenoid objects (pass in channel as parameter) self.solenoids = [self.hub.makeSolenoid(0), self.hub.makeSolenoid(1)] # make double solenoid objects (pass in forward channel and reverse channel as parameters) self.double_solenoids = [self.hub.makeDoubleSolenoid(2, 3), self.hub.makeDoubleSolenoid(4, 5)] # make compressor self.compressor = self.hub.makeCompressor(1) self.timer = wpilib.Timer self.input = wpilib.Joystick(0) def teleopInit(self): print("Starting Compressor") self.compressor.enableDigital() for solenoid in self.double_solenoids: solenoid.set(wpilib.DoubleSolenoid.Value.kOff) def teleopPeriodic(self): if self.input.getRawButtonPressed(5): # LB (Xbox) print("Toggling First...") for solenoid in self.double_solenoids: solenoid.toggle() if self.input.getRawButtonPressed(6): # RB (Xbox) print("Toggling Second...") for solenoid in self.double_solenoids: solenoid.toggle() def teleopExit(self): print("Turning off compressor...") self.compressor.disable() if __name__ == "__main__": wpilib.run(MyRobot)
1,469
Python
29.624999
102
0.628319
RoboEagles4828/edna2023/rio/POC/motion_magic_poc/MotionProfile.py
import argparse import logging import math from collections import deque import copy import matplotlib.pyplot as plt logger = logging.getLogger(f"{__name__}") #Constants VPROG = 4.00 T1 = 400 T2 = 200 ITP = 10 if __name__ == '__main__': # Instantiate the parser parser = argparse.ArgumentParser(description='Talon SRX motion profiler') # Required Positional Arguments parser.add_argument('-d', '--distance', type=str, required=True, help="Distance to move") parser.add_argument('-l', "--loglevel", type=str, default='INFO', help="logging level") parser.add_argument('-v', '--max_vel', type=str, help="max velocity", default="4.0") parser.add_argument('-a', '--max_accel', type=str, help="max_acclereation", default="10.0") args = parser.parse_args() # Setup logger numeric_level = getattr(logging, args.loglevel.upper(), None) if not isinstance(numeric_level, int): raise ValueError(f"Invalid log level: {args.loglevel}") logging.basicConfig(format='%(asctime)s-%(levelname)s-%(message)s', datefmt='%H:%M:%S', level=numeric_level) VPROG = float(args.max_vel) max_accel = float(args.max_accel) if max_accel != 0.0: T1 = VPROG/max_accel * 1000 # Calculation constants dist = float(args.distance) t4 = (dist/VPROG) * 1000 fl1 = float(math.trunc(T1 / ITP)) fl2 = math.trunc(T2 / ITP) N = float(t4 / ITP) step = 1 time = 0.0 velocity = 0.0 input = False runningSum = deque(fl2*[0.0], fl2) trajectory = list() trajectory.append({"step": step, "time": time, "velocity": velocity}) runningSum.append(0.0) zeropt = list() # Now we print out the trajectory fs1 = 0.0 exit = False while not exit: step += 1 time = ((step - 1) * ITP)/1000 input = 1 if step < (N+2) else 0 addition = (1/fl1) if input==1 else (-1/fl1) fs1 = max(0, min(1, fs1 + addition)) # logging.log(numeric_level, f"fs1 = {fs1}") fs2 = sum(runningSum) # logging.log(numeric_level, f"fs2 = {fs2}") runningSum.append(fs1) if fs1 == 0: if fs2 == 0: zeropt.append(1) else: zeropt.append(0) else: zeropt.append(0) output_included = 1 if sum(zeropt[0:step]) <= 2 else 0 if output_included == 1: velocity = ((fs1+fs2)/(1.0/fl2))*VPROG if fs2 != 0 else 0 trajectory.append({"step": step, "time": time, "velocity": velocity}) else: exit = True logging.log(numeric_level, "EXITTING") print(trajectory) x = list() y = list() for i in trajectory: x.append(i["time"]) y.append(i["velocity"]) plt.plot(x, y) plt.xlabel("TIME") plt.ylabel("VELOCITY") plt.show()
2,915
Python
29.061855
95
0.568782
RoboEagles4828/edna2023/rio/POC/motion_magic_poc/test.py
import math # 90 degrees testVal = math.pi / 4 # go down 180 degrees modifyVal = math.pi # Get remainder result = math.fmod(testVal - modifyVal, 2 * math.pi) print(result) # theory moveDown = modifyVal - testVal result2 = (2 * math.pi) - moveDown print(result2) # Correction for negative values result += (2 * math.pi) print(result) assert result == result2
364
Python
14.869565
52
0.708791
RoboEagles4828/edna2023/rio/POC/motion_magic_poc/robot.py
import logging import wpilib import ctre import math # Ports motorPort = 7 controllerPort = 0 encoderPort = 8 # PID Constants pid_constants = { "kP": 0.2, "kI": 0.0, "kD": 0.1, "kF": 0.2, "kIzone": 0, "kPeakOutput": 1.0 } slot_idx = 0 pid_loop_idx = 0 timeout_ms = 30 # Motor Constants DRIVE_RATIO = 6.75 STEER_RATIO = 150.0/7.0 motor_ticks_per_rev = 2048.0 nominal_voltage = 12.0 steer_current_limit = 20.0 # Encoder Constants encoder_ticks_per_rev = 4096.0 encoder_offset = 0 encoder_direction = False encoder_reset_velocity = math.radians(0.5) encoder_reset_iterations = 500 # Demo Behavior # Range: 0 - 2pi velocityConstant = 1.0 accelerationConstant = 0.5 increment = math.pi / 8 # Conversion Functions # This is thought of as radians per shaft tick times the ratio to the axle (steer) positionCoefficient = 2.0 * math.pi / motor_ticks_per_rev / STEER_RATIO # This is the same conversion with time in mind. velocityCoefficient = positionCoefficient * 10.0 # axle (radians) -> shaft (ticks) def getShaftTicks(radians, type): if type == "position": return radians / positionCoefficient elif type == "velocity": return radians / velocityCoefficient else: return 0 # shaft (ticks) -> axle (radians) def getAxleRadians(ticks, type): if type == "position": return ticks * positionCoefficient elif type == "velocity": return ticks * velocityCoefficient else: return 0 ######### Robot Class ######### class motor_poc(wpilib.TimedRobot): def robotInit(self) -> None: logging.info("Entering Robot Init") # Configure Joystick self.joystick = wpilib.XboxController(controllerPort) # Configure CANCoder canCoderConfig = ctre.CANCoderConfiguration() canCoderConfig.absoluteSensorRange = ctre.AbsoluteSensorRange.Unsigned_0_to_360 canCoderConfig.initializationStrategy = ctre.SensorInitializationStrategy.BootToAbsolutePosition canCoderConfig.magnetOffsetDegrees = encoder_offset canCoderConfig.sensorDirection = encoder_direction # Setup encoder to be in radians canCoderConfig.sensorCoefficient = 2 * math.pi / encoder_ticks_per_rev canCoderConfig.unitString = "rad" canCoderConfig.sensorTimeBase = ctre.SensorTimeBase.PerSecond self.encoder = ctre.CANCoder(encoderPort) self.encoder.configAllSettings(canCoderConfig, timeout_ms) self.encoder.setPositionToAbsolute(timeout_ms) self.encoder.setStatusFramePeriod(ctre.CANCoderStatusFrame.SensorData, 10, timeout_ms) # Configure Talon self.talon = ctre.TalonFX(motorPort) self.talon.configFactoryDefault() self.talon.configSelectedFeedbackSensor(ctre.TalonFXFeedbackDevice.IntegratedSensor, pid_loop_idx, timeout_ms) self.talon.configNeutralDeadband(0.01, timeout_ms) self.talon.setSensorPhase(True) self.talon.setInverted(True) self.talon.setStatusFramePeriod(ctre.StatusFrameEnhanced.Status_13_Base_PIDF0, 10, timeout_ms) self.talon.setStatusFramePeriod(ctre.StatusFrameEnhanced.Status_10_MotionMagic, 10, timeout_ms) self.talon.configNominalOutputForward(0, timeout_ms) self.talon.configNominalOutputReverse(0, timeout_ms) self.talon.configPeakOutputForward(1, timeout_ms) self.talon.configPeakOutputReverse(-1, timeout_ms) self.talon.selectProfileSlot(slot_idx, pid_loop_idx) self.talon.config_kP(slot_idx, pid_constants["kP"], timeout_ms) self.talon.config_kI(slot_idx, pid_constants["kI"], timeout_ms) self.talon.config_kD(slot_idx, pid_constants["kD"], timeout_ms) # TODO: Figure out Magic Numbers and Calculations Below self.talon.config_kF(slot_idx, (1023.0 * velocityCoefficient / nominal_voltage) * velocityConstant, timeout_ms) self.talon.configMotionCruiseVelocity(2.0 / velocityConstant / velocityCoefficient, timeout_ms) self.talon.configMotionAcceleration((8.0 - 2.0) / accelerationConstant / velocityCoefficient, timeout_ms) self.talon.configMotionSCurveStrength(1) # Set Sensor Position to match Absolute Position of CANCoder self.talon.setSelectedSensorPosition(getShaftTicks(self.encoder.getAbsolutePosition(), "position"), pid_loop_idx, timeout_ms) self.talon.configVoltageCompSaturation(nominal_voltage, timeout_ms) currentLimit = ctre.SupplyCurrentLimitConfiguration() currentLimit.enable = True currentLimit.currentLimit = steer_current_limit self.talon.configSupplyCurrentLimit(currentLimit, timeout_ms) self.talon.enableVoltageCompensation(True) self.talon.setNeutralMode(ctre.NeutralMode.Brake) # Keep track of position self.targetPosition = 0 self.reset_iterations = 0 def teleopInit(self) -> None: logging.info("Entering Teleop") def teleopPeriodic(self) -> None: # Get position and velocities of the motor motorPosition = getAxleRadians(self.talon.getSelectedSensorPosition(), "position") motorVelocity = getAxleRadians(self.talon.getSelectedSensorVelocity(), "velocity") absolutePosition = self.encoder.getAbsolutePosition() # Reset if motorVelocity < encoder_reset_velocity: self.reset_iterations += 1 if self.reset_iterations >= encoder_reset_iterations: self.reset_iterations = 0 self.talon.setSelectedSensorPosition(getShaftTicks(absolutePosition, "position")) motorPosition = absolutePosition else: self.reset_iterations = 0 # Increment Target Position if self.joystick.getAButtonPressed(): self.targetPosition += increment elif self.joystick.getBButtonPressed(): self.targetPosition -= increment # Move back in 0 - 2pi range in case increment kicked us out self.targetPosition = math.fmod(self.targetPosition, 2.0 * math.pi) # This correction is needed in case we got a negative remainder # A negative radian can be thought of as starting at 2pi and moving down abs(remainder) if self.targetPosition < 0.0: self.targetPosition += 2.0 * math.pi # Now that we have a new target position, we need to figure out how to move the motor. # First let's assume that we will move directly to the target position. newMotorPosition = self.targetPosition # The motor could get to the target position by moving clockwise or counterclockwise. # The shortest path should be the direction that is less than pi radians away from the current motor position. # The shortest path could loop around the circle and be less than 0 or greater than 2pi. # We need to get the absolute current position to determine if we need to loop around the 0 - 2pi range. # The current motor position does not stay inside the 0 - 2pi range. # We need the absolute position to compare with the target position. absoluteMotorPosition = math.fmod(motorPosition, 2.0 * math.pi) if absoluteMotorPosition < 0.0: absoluteMotorPosition += 2.0 * math.pi # If the target position was in the first quadrant area # and absolute motor position was in the last quadrant area # then we need to move into the next loop around the circle. if self.targetPosition - absoluteMotorPosition < -math.pi: newMotorPosition += 2.0 * math.pi # If the target position was in the last quadrant area # and absolute motor position was in the first quadrant area # then we need to move into the previous loop around the circle. elif self.targetPosition - absoluteMotorPosition > math.pi: newMotorPosition -= 2.0 * math.pi # Last, add the current existing loops that the motor has gone through. newMotorPosition += motorPosition - absoluteMotorPosition print(f"ABS Target: {self.targetPosition} Motor Target: {newMotorPosition} Motor Current: {motorPosition} ABS Current: {absolutePosition}") self.talon.set(ctre.TalonFXControlMode.MotionMagic, getShaftTicks(newMotorPosition, "position")) def teleopExit(self) -> None: logging.info("Exiting Teleop") if __name__ == '__main__': wpilib.run(motor_poc)
8,490
Python
41.243781
156
0.690813
RoboEagles4828/edna2023/rio/POC/limitswitch_test/robot.py
import wpilib class MyRobot(wpilib.TimedRobot): def robotInit(self): print("Initalizing") self.limitSwitch = wpilib.DigitalInput(0) self.pastState = 0 self.timer = wpilib.Timer self.input = wpilib.Joystick(0) def teleopInit(self): print("Entering teleop") def teleopPeriodic(self): if (self.limitSwitch.get() != self.pastState): print(f"State Changed from {self.pastState} to {self.limitSwitch.get()}") self.pastState = self.limitSwitch.get() def teleopExit(self): print("Exitted teleop") if __name__ == "__main__": wpilib.run(MyRobot)
650
Python
26.124999
85
0.616923
RoboEagles4828/rift2024/docker-compose.yml
version: "3.6" services: main_control: # image: "ghcr.io/roboeagles4828/developer-environment:7" image: "ghcr.io/roboeagles4828/jetson:4" network_mode: "host" privileged: true environment: - ROS_DOMAIN_ID=0 - FASTRTPS_DEFAULT_PROFILES_FILE=/usr/local/share/middleware_profiles/rtps_udp_profile.xml deploy: restart_policy: 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}/rift2024:/opt/workspace zed_cam: image: ghcr.io/roboeagles4828/jetson-zed:2 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 - /dev/*:/dev/* - ${HOME}/rift2024/src/rift_bringup/config/zed_config-common-custom-box.yaml:/root/ros2_ws/src/zed-ros2-wrapper/zed_wrapper/config/common.yaml - ${HOME}/rift2024/model.engine:/root/ros2_ws/model.engine - ${HOME}/rift2024/scripts/config/SN39192289.conf:/usr/local/zed/settings/SN39192289.conf - ${HOME}/rift2024/src/rift_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,881
YAML
44.746031
148
0.67789
RoboEagles4828/rift2024/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/rift2024/README.md
# rift2024 2024 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 Rift ### 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 `pysim` inside a new devcontainer terminal (this is the simulated driverstation window) 6. Run `launch isaac_pysim` inside a new devcontainer terminal 7. Run auton/teleop by enabling in the simulated driverstation window ### In real life 1. Connect an xbox controller 2. Launch FRC Driverstation 3. Launch WPILib Shuffleboard 4. Select auton/teleop 5. Press Enable
1,824
Markdown
23.333333
94
0.730263
RoboEagles4828/rift2024/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/rift2024/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/rift2024/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/rift2024/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/rift2024/src/joint_trajectory_teleop/joint_trajectory_teleop/yaml_test.py
import yaml yaml_path = '/workspaces/rift2024/src/rift_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/rift2024/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/rift_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/rift2024/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/rift2024/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,877
C++
37.316129
153
0.678117
RoboEagles4828/rift2024/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/rift2024/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/rift2024/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/rift2024/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/rift2024/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/rift2024/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/rift2024/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/rift2024/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/rift2024/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 "rift_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<rift_interfaces::srv::SetBool::Request> request, std::shared_ptr<rift_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<rift_interfaces::srv::SetBool>::SharedPtr reset_orientation_service; rclcpp::TimerBase::SharedPtr timer_callback_; rclcpp::Client<rift_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<rift_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<rift_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<rift_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<rift_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<rift_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<rift_interfaces::srv::SetBool::Request> request, std::shared_ptr<rift_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/rift2024/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/rift2024/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/rift2024/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/rift2024/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/rift2024/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/rift2024/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/rift2024/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/rift2024/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 rift_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/rift2024/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/rift2024/isaac/Eaglegym/eaglegym/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,975
Python
35.74074
110
0.592941
RoboEagles4828/rift2024/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 rift_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/rift_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/rift2024/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/rift2024/src/policy_runner/setup.py
from setuptools import setup package_name = 'policy_runner' 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', 'rl-games'], zip_safe=True, maintainer='admin', maintainer_email='[email protected]', description='TODO: Package description', license='TODO: License declaration', tests_require=['pytest'], entry_points={ 'console_scripts': [ 'runner = policy_runner.policy_runner:main', 'odom = policy_runner.odom_test:main' ], }, )
743
Python
25.571428
56
0.597577
RoboEagles4828/rift2024/src/policy_runner/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/rift2024/src/policy_runner/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/rift2024/src/policy_runner/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/rift2024/src/policy_runner/policy_runner/odom_test.py
import rclpy from rclpy.node import Node from nav_msgs.msg import Odometry from std_msgs.msg import String class Odom(Node): def __init__(self): super().__init__("odom_publisher") self.publisher = self.create_publisher(Odometry, '/real/odom', 10) self.obj_publisher = self.create_publisher(String, '/real/obj_det_pose', 10) self.declare_parameter('obj_string',"0.0|0.0|0.0") self.declare_parameter("publish_odom", True) self.declare_parameter("publish_zed", True) self.odom_msg = Odometry() self.get_logger().info("\033[92m" + "Odom Publisher Started" + "\033[0m") self.timer = self.create_timer(0.1, self.timer_callback) def timer_callback(self): odom = self.get_parameter("publish_odom").get_parameter_value().bool_value zed = self.get_parameter("publish_zed").get_parameter_value().bool_value if odom: self.publisher.publish(self.odom_msg) if zed: self.obj_publisher.publish(String(data=self.get_parameter('obj_string').get_parameter_value().string_value)) if odom and not zed: self.get_logger().info("Publishing Odom") elif zed and not odom: self.get_logger().info("Publishing Zed") elif odom and zed: self.get_logger().info("Publishing Odom and Zed") else: self.get_logger().info("Not Publishing") def main(args=None): rclpy.init(args=args) odom = Odom() rclpy.spin(odom) odom.destroy_node() rclpy.shutdown()
1,594
Python
37.902438
120
0.611041
RoboEagles4828/rift2024/src/policy_runner/policy_runner/policy_runner.py
import rclpy from rclpy.node import Node from std_msgs.msg import Float32, String from nav_msgs.msg import Odometry from sensor_msgs.msg import JointState from geometry_msgs.msg import Twist import numpy as np import torch import torch.nn as nn from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint import math from rl_games.algos_torch.models import ModelA2CContinuous from rl_games.algos_torch.torch_ext import load_checkpoint from rl_games.algos_torch.network_builder import A2CBuilder from rl_games.common.a2c_common import ContinuousA2CBase import yaml class Reader(Node): def __init__(self): super().__init__("reinforcement_learning_runner") # self.robot_ip = robot_ip # self.policy = torch.load("/workspaces/rift2024/isaac/Eaglegym/eaglegym/runs/RiftK/nn/RiftK.pth") self.policy = self.load_checkpoint("/workspaces/rift2024/isaac/Eaglegym/eaglegym/runs/RiftK/nn/RiftK_1050.pth") self.joint_action_pub = self.create_publisher(String, "/real/cmd_vel", 10) # self.joint_trajectory_action_pub = self.create_publisher(Twist, "joint_trajectory_message", 10) self.declare_parameter("odom_topic", "/real/odom") self.declare_parameter("target_topic", "/real/obj_det_pose") self.odom_topic = self.get_parameter("odom_topic").get_parameter_value().string_value self.target_topic = self.get_parameter("target_topic").get_parameter_value().string_value self.odom_sub = self.create_subscription(Odometry, self.odom_topic, self.odom_callback, 10) self.target_sub = self.create_subscription(String, self.target_topic, self.target_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.i = 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', # ] self.target_pos = [] self.get_logger().info("\033[92m" + "Policy Runner Started" + "\033[0m") def load_checkpoint(self, filepath): config = yaml.load(open("/workspaces/rift2024/isaac/Eaglegym/eaglegym/cfg/train/RiftKPPO.yaml", "r"), Loader=yaml.FullLoader) config = config["params"] state = load_checkpoint(filepath) state_dict = {k.replace('a2c_network.', ''): v for k, v in state['model'].items()} builder = A2CBuilder() builder.load(config["network"]) network = builder.build("network", actions_num=10, input_shape=(13,)) model_state_dict = network.state_dict() state_dict = {k: v for k, v in state_dict.items() if k in model_state_dict} network.load_state_dict(state_dict) network.eval() network.train(False) return network # model = checkpoint['model'] # model.load_state_dict(checkpoint) # for parameter in model.parameters(): # parameter.requires_grad = False # model.eval() # return model def get_action(self, msg): ''' Gym obs type for RiftK: [0:3] = ([target_pos] - [robot_pos]) / 3 # x, y, z [3:7] = [robot_rotation_quaternion] # x, y, z, w [7:10] = [robot_linear_velocities] / 2 # x, y, z [10:13] = [robot_angular_velocities] / M_PI # x, y, z Input type String: 0,1,2,3,4,5,6,7,8,9,10,11,12,13 ''' # convert string to list input_obs = msg.data.split(",") obs = np.array(input_obs, dtype=np.float32) obs = torch.tensor(obs).float() obs = obs.unsqueeze(0) observation = {"obs": obs} action = self.policy(observation) vel = action[0].detach().numpy()[0] self.get_logger().info("Full Action: " + np.array_str(vel, precision=2)) # vel = [self.limit(i) for i in vel] # ======================= convert action to twist message =================================== self.twist_msg.linear.x = float(vel[0]) self.twist_msg.linear.y = float(vel[1]) self.twist_msg.linear.z = float(vel[2]) # 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) output = String() output.data = f"{-vel[1]}|{-vel[0]}|{vel[2]}" # if self.target_pos == [0, 0, 0]: # output.data = f"0.0|0.0|0.0" # vel = [0.0, 0.0, 0.0] self.print_in_color(f"Action: {str(vel[0:3])}", "blue") self.joint_action_pub.publish(output) self.step += 1 def limit(self, value): speed = 0 if value > 1: speed = 1 elif value < -1: speed = -1 else: speed = value return speed / 10 def odom_callback(self, msg: Odometry): if(msg != None and len(self.target_pos) > 0): self.odom_msg = msg obs_string = String() robot_pos = [ float(self.odom_msg.pose.pose.position.x), float(self.odom_msg.pose.pose.position.y), float(self.odom_msg.pose.pose.position.z) ] robot_rot_quat = [ float(self.odom_msg.pose.pose.orientation.x), float(self.odom_msg.pose.pose.orientation.y), float(self.odom_msg.pose.pose.orientation.z), float(self.odom_msg.pose.pose.orientation.w) ] robot_linear_vel = [ float(self.odom_msg.twist.twist.linear.x), float(self.odom_msg.twist.twist.linear.y), float(self.odom_msg.twist.twist.linear.z) ] robot_angular_vel = [ float(self.odom_msg.twist.twist.angular.x), float(self.odom_msg.twist.twist.angular.y), float(self.odom_msg.twist.twist.angular.z) ] obs_input = [ (self.target_pos[0] - robot_pos[0]), (self.target_pos[1] - robot_pos[1]), (self.target_pos[2] - robot_pos[2]), robot_rot_quat[0], robot_rot_quat[1], robot_rot_quat[2], robot_rot_quat[3], robot_linear_vel[0], robot_linear_vel[1], robot_linear_vel[2], robot_angular_vel[0], robot_angular_vel[1], robot_angular_vel[2] ] obs_string.data = ",".join([str(i) for i in obs_input]) obs_dict = { "target position": self.target_pos, "robot position": robot_pos, "robot rotation quaternion": robot_rot_quat, "robot linear velocity": robot_linear_vel, "robot angular velocity": robot_angular_vel } self.print_in_color(f"Observation: {obs_dict}", "blue") self.get_action(obs_string) return def target_callback(self, msg): if(msg != None): self.target_pos = msg.data.split("|") self.target_pos = [float(i) for i in self.target_pos] return def get_reward(): return def print_in_color(self, msg, color): if(color == "green"): self.get_logger().info("\033[92m" + msg + "\033[0m") elif(color == "blue"): self.get_logger().info("\033[94m" + msg + "\033[0m") elif(color == "red"): self.get_logger().info("\033[91m" + msg + "\033[0m") else: self.get_logger().info(msg) 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()
9,125
Python
35.798387
133
0.528986
RoboEagles4828/rift2024/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/rift2024/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
RoboEagles4828/rift2024/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> command_position, std::reference_wrapper<const hardware_interface::LoanedStateInterface> state_position, std::string name) : command_position_(command_position), state_position_(state_position), name(std::move(name)) {} void Axle::set_position(double position) { command_position_.get().set_value(position); } double Axle::get_position(void) { // temporary return state_position_.get().get_value(); } void optimize(double& target, const double& current, double& wheel_velocity) { double target_copy = target; double diff = target_copy - current; // Check one way if (diff > M_PI) { target_copy -= 2.0 * M_PI; } else if (diff < -M_PI) { target_copy += 2.0 * M_PI; } // Check other way diff = target_copy - current; if(std::abs(diff) > M_PI / 2.0) { // Get better position 180 degrees away if (target < 0.0) { target += M_PI; } else { target -= M_PI; } // Reverse direction wheel_velocity *= -1.0; } } SwerveController::SwerveController() : controller_interface::ControllerInterface() {} controller_interface::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_meters", wheel_params_.x_offset); auto_declare<double>("chassis_width_meters", wheel_params_.y_offset); auto_declare<double>("wheel_radius_meters", wheel_params_.radius); auto_declare<double>("max_wheel_angular_velocity", max_wheel_angular_velocity_); auto_declare<double>("cmd_vel_timeout_seconds", cmd_vel_timeout_milliseconds_.count() / 1000.0); auto_declare<bool>("use_stamped_vel", use_stamped_vel_); // Limits auto_declare<bool>("linear.x.has_velocity_limits", false); auto_declare<bool>("linear.x.has_acceleration_limits", false); auto_declare<bool>("linear.x.has_jerk_limits", false); auto_declare<double>("linear.x.max_velocity", 0.0); auto_declare<double>("linear.x.min_velocity", 0.0); auto_declare<double>("linear.x.max_acceleration", 0.0); auto_declare<double>("linear.x.min_acceleration", 0.0); auto_declare<double>("linear.x.max_jerk", 0.0); auto_declare<double>("linear.x.min_jerk", 0.0); auto_declare<bool>("linear.y.has_velocity_limits", false); auto_declare<bool>("linear.y.has_acceleration_limits", false); auto_declare<bool>("linear.y.has_jerk_limits", false); auto_declare<double>("linear.y.max_velocity", 0.0); auto_declare<double>("linear.y.min_velocity", 0.0); auto_declare<double>("linear.y.max_acceleration", 0.0); auto_declare<double>("linear.y.min_acceleration", 0.0); auto_declare<double>("linear.y.max_jerk", 0.0); auto_declare<double>("linear.y.min_jerk", 0.0); auto_declare<bool>("angular.z.has_velocity_limits", false); auto_declare<bool>("angular.z.has_acceleration_limits", false); auto_declare<bool>("angular.z.has_jerk_limits", false); auto_declare<double>("angular.z.max_velocity", 0.0); auto_declare<double>("angular.z.min_velocity", 0.0); auto_declare<double>("angular.z.max_acceleration", 0.0); auto_declare<double>("angular.z.min_acceleration", 0.0); auto_declare<double>("angular.z.max_jerk", 0.0); auto_declare<double>("angular.z.min_jerk", 0.0); } catch (const std::exception &e) { fprintf(stderr, "Exception thrown during init stage with message: %s \n", e.what()); return controller_interface::CallbackReturn::ERROR; } return controller_interface::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 { std::vector<std::string> conf_names; 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}; } controller_interface::return_type SwerveController::update( const rclcpp::Time &time, const rclcpp::Duration & period) { auto logger = get_node()->get_logger(); auto clk = * get_node()->get_clock(); 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_milliseconds_) // { // halt(); // } // INPUTS Twist command = *last_command_msg; auto & last_command = previous_commands_.back().twist; auto & second_to_last_command = previous_commands_.front().twist; double &linear_x_velocity_comand = command.twist.linear.x; double &linear_y_velocity_comand = command.twist.linear.y; double &angular_velocity_comand = command.twist.angular.z; double original_linear_x_velocity_comand = linear_x_velocity_comand; double original_linear_y_velocity_comand = linear_y_velocity_comand; double original_angular_velocity_comand = angular_velocity_comand; // Limits limiter_linear_X_.limit(linear_x_velocity_comand, last_command.linear.x, second_to_last_command.linear.x, period.seconds()); limiter_linear_Y_.limit(linear_y_velocity_comand, last_command.linear.y, second_to_last_command.linear.y, period.seconds()); limiter_angular_Z_.limit(angular_velocity_comand, last_command.angular.z, second_to_last_command.angular.z, period.seconds()); previous_commands_.pop(); previous_commands_.emplace(command); if (linear_x_velocity_comand != original_linear_x_velocity_comand) { RCLCPP_WARN_THROTTLE(logger, clk, 1000, "Limiting Linear X %f -> %f", original_linear_x_velocity_comand, linear_x_velocity_comand); } if (linear_y_velocity_comand != original_linear_y_velocity_comand) { RCLCPP_WARN_THROTTLE(logger, clk, 1000, "Limiting Linear Y %f -> %f", original_linear_y_velocity_comand, linear_y_velocity_comand); } if (angular_velocity_comand != original_angular_velocity_comand) { RCLCPP_WARN_THROTTLE(logger, clk, 1000, "Limiting Angular Z %f -> %f", original_angular_velocity_comand, angular_velocity_comand); } double x_offset = wheel_params_.x_offset; double radius = wheel_params_.radius; // get current wheel positions const double front_left_current_pos = front_left_axle_command_handle_->get_position(); const double front_right_current_pos = front_right_axle_command_handle_->get_position(); const double rear_left_current_pos = rear_left_axle_command_handle_->get_position(); const double rear_right_current_pos = rear_right_axle_command_handle_->get_position(); // Compute Wheel Velocities and Positions const double a = (linear_y_velocity_comand * -1.0) - angular_velocity_comand * x_offset / 2.0; const double b = (linear_y_velocity_comand * -1.0) + angular_velocity_comand * x_offset / 2.0; const double c = linear_x_velocity_comand - angular_velocity_comand * x_offset / 2.0; const double d = linear_x_velocity_comand + angular_velocity_comand * x_offset / 2.0; double front_left_velocity = sqrt(pow(b, 2) + pow(d, 2)) / radius; double front_right_velocity = sqrt(pow(b, 2) + pow(c, 2)) / radius; double rear_left_velocity = sqrt(pow(a, 2) + pow(d, 2)) / radius; double rear_right_velocity = sqrt(pow(a, 2) + pow(c, 2)) / radius; // Normalize wheel velocities if any are greater than max double velMax = std::max({front_left_velocity, front_right_velocity, rear_left_velocity, rear_right_velocity}); if (velMax > max_wheel_angular_velocity_) { front_left_velocity = front_left_velocity/velMax * max_wheel_angular_velocity_; front_right_velocity = front_right_velocity/velMax * max_wheel_angular_velocity_; rear_left_velocity = rear_left_velocity/velMax * max_wheel_angular_velocity_; rear_right_velocity = rear_right_velocity/velMax * max_wheel_angular_velocity_; } double front_left_position; double front_right_position ; double rear_left_position; double rear_right_position; // Make position current if no movement is given if (std::abs(linear_x_velocity_comand) <= 0.1 && std::abs(linear_y_velocity_comand) <= 0.1 && std::abs(angular_velocity_comand) <= 0.1) { front_left_position = front_left_current_pos; front_right_position = front_right_current_pos; rear_left_position = rear_left_current_pos; rear_right_position = rear_right_current_pos; } else { front_left_position = atan2(b, d); front_right_position = atan2(b, c); rear_left_position = atan2(a, d); rear_right_position = atan2(a, c); // Optimization optimize(front_left_position, front_left_current_pos, front_left_velocity); optimize(front_right_position, front_right_current_pos, front_right_velocity); optimize(rear_left_position, rear_left_current_pos, rear_left_velocity); optimize(rear_right_position, rear_right_current_pos, rear_right_velocity); } // Old Limit Wheel Velocity // front_left_velocity=limiter_wheel_.limit(front_left_velocity,last_wheel_commands[0], second_last_wheel_commands[0],0.1); // front_right_velocity=limiter_wheel_.limit(front_right_velocity,last_wheel_commands[1], second_last_wheel_commands[1],0.1); // rear_left_velocity=limiter_wheel_.limit(rear_left_velocity,last_wheel_commands[2], second_last_wheel_commands[2],0.1); // rear_right_velocity=limiter_wheel_.limit(rear_right_velocity,last_wheel_commands[3], second_last_wheel_commands[3],0.1); // second_last_wheel_commands= last_wheel_commands; front_left_wheel_command_handle_->set_velocity(front_left_velocity); front_right_wheel_command_handle_->set_velocity(front_right_velocity); rear_left_wheel_command_handle_->set_velocity(rear_left_velocity); rear_right_wheel_command_handle_->set_velocity(rear_right_velocity); front_left_axle_command_handle_->set_position(front_left_position); front_right_axle_command_handle_->set_position(front_right_position); rear_left_axle_command_handle_->set_position(rear_left_position); rear_right_axle_command_handle_->set_position(rear_right_position); // Time update const auto update_dt = current_time - previous_update_timestamp_; previous_update_timestamp_ = current_time; return controller_interface::return_type::OK; } controller_interface::CallbackReturn SwerveController::on_configure(const rclcpp_lifecycle::State &) { auto logger = get_node()->get_logger(); limiter_linear_X_ = SpeedLimiter( get_node()->get_parameter("linear.x.has_velocity_limits").as_bool(), get_node()->get_parameter("linear.x.has_acceleration_limits").as_bool(), get_node()->get_parameter("linear.x.has_jerk_limits").as_bool(), get_node()->get_parameter("linear.x.min_velocity").as_double(), get_node()->get_parameter("linear.x.max_velocity").as_double(), get_node()->get_parameter("linear.x.min_acceleration").as_double(), get_node()->get_parameter("linear.x.max_acceleration").as_double(), get_node()->get_parameter("linear.x.min_jerk").as_double(), get_node()->get_parameter("linear.x.max_jerk").as_double()); RCLCPP_WARN(logger, "Linear X Limiter Velocity Limits: %f, %f", limiter_linear_X_.min_velocity_, limiter_linear_X_.max_velocity_); RCLCPP_WARN(logger, "Linear X Limiter Acceleration Limits: %f, %f", limiter_linear_X_.min_acceleration_, limiter_linear_X_.max_acceleration_); RCLCPP_WARN(logger, "Linear X Limiter Jert Limits: %f, %f", limiter_linear_X_.min_jerk_, limiter_linear_X_.max_jerk_); limiter_linear_Y_ = SpeedLimiter( get_node()->get_parameter("linear.y.has_velocity_limits").as_bool(), get_node()->get_parameter("linear.y.has_acceleration_limits").as_bool(), get_node()->get_parameter("linear.y.has_jerk_limits").as_bool(), get_node()->get_parameter("linear.y.min_velocity").as_double(), get_node()->get_parameter("linear.y.max_velocity").as_double(), get_node()->get_parameter("linear.y.min_acceleration").as_double(), get_node()->get_parameter("linear.y.max_acceleration").as_double(), get_node()->get_parameter("linear.y.min_jerk").as_double(), get_node()->get_parameter("linear.y.max_jerk").as_double()); RCLCPP_WARN(logger, "Linear Y Limiter Velocity Limits: %f, %f", limiter_linear_Y_.min_velocity_, limiter_linear_Y_.max_velocity_); RCLCPP_WARN(logger, "Linear Y Limiter Acceleration Limits: %f, %f", limiter_linear_Y_.min_acceleration_, limiter_linear_Y_.max_acceleration_); RCLCPP_WARN(logger, "Linear Y Limiter Jert Limits: %f, %f", limiter_linear_Y_.min_jerk_, limiter_linear_Y_.max_jerk_); limiter_angular_Z_ = SpeedLimiter( get_node()->get_parameter("angular.z.has_velocity_limits").as_bool(), get_node()->get_parameter("angular.z.has_acceleration_limits").as_bool(), get_node()->get_parameter("angular.z.has_jerk_limits").as_bool(), get_node()->get_parameter("angular.z.min_velocity").as_double(), get_node()->get_parameter("angular.z.max_velocity").as_double(), get_node()->get_parameter("angular.z.min_acceleration").as_double(), get_node()->get_parameter("angular.z.max_acceleration").as_double(), get_node()->get_parameter("angular.z.min_jerk").as_double(), get_node()->get_parameter("angular.z.max_jerk").as_double()); RCLCPP_WARN(logger, "Angular Z Limiter Velocity Limits: %f, %f", limiter_angular_Z_.min_velocity_, limiter_angular_Z_.max_velocity_); RCLCPP_WARN(logger, "Angular Z Limiter Acceleration Limits: %f, %f", limiter_angular_Z_.min_acceleration_, limiter_angular_Z_.max_acceleration_); RCLCPP_WARN(logger, "Angular Z Limiter Jert Limits: %f, %f", limiter_angular_Z_.min_jerk_, limiter_angular_Z_.max_jerk_); // Get Parameters front_left_wheel_joint_name_ = get_node()->get_parameter("front_left_wheel_joint").as_string(); front_right_wheel_joint_name_ = get_node()->get_parameter("front_right_wheel_joint").as_string(); rear_left_wheel_joint_name_ = get_node()->get_parameter("rear_left_wheel_joint").as_string(); rear_right_wheel_joint_name_ = get_node()->get_parameter("rear_right_wheel_joint").as_string(); front_left_axle_joint_name_ = get_node()->get_parameter("front_left_axle_joint").as_string(); front_right_axle_joint_name_ = get_node()->get_parameter("front_right_axle_joint").as_string(); rear_left_axle_joint_name_ = get_node()->get_parameter("rear_left_axle_joint").as_string(); rear_right_axle_joint_name_ = get_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 controller_interface::CallbackReturn::ERROR; } if (front_right_wheel_joint_name_.empty()) { RCLCPP_ERROR(logger, "front_right_wheel_joint_name is not set"); return controller_interface::CallbackReturn::ERROR; } if (rear_left_wheel_joint_name_.empty()) { RCLCPP_ERROR(logger, "rear_left_wheel_joint_name is not set"); return controller_interface::CallbackReturn::ERROR; } if (rear_right_wheel_joint_name_.empty()) { RCLCPP_ERROR(logger, "rear_right_wheel_joint_name is not set"); return controller_interface::CallbackReturn::ERROR; } if (front_left_axle_joint_name_.empty()) { RCLCPP_ERROR(logger, "front_left_axle_joint_name is not set"); return controller_interface::CallbackReturn::ERROR; } if (front_right_axle_joint_name_.empty()) { RCLCPP_ERROR(logger, "front_right_axle_joint_name is not set"); return controller_interface::CallbackReturn::ERROR; } if (rear_left_axle_joint_name_.empty()) { RCLCPP_ERROR(logger, "rear_left_axle_joint_name is not set"); return controller_interface::CallbackReturn::ERROR; } if (rear_right_axle_joint_name_.empty()) { RCLCPP_ERROR(logger, "rear_right_axle_joint_name is not set"); return controller_interface::CallbackReturn::ERROR; } wheel_params_.x_offset = get_node()->get_parameter("chassis_length_meters").as_double(); wheel_params_.y_offset = get_node()->get_parameter("chassis_width_meters").as_double(); wheel_params_.radius = get_node()->get_parameter("wheel_radius_meters").as_double(); max_wheel_angular_velocity_ = get_node()->get_parameter("max_wheel_angular_velocity").as_double(); cmd_vel_timeout_milliseconds_ = std::chrono::milliseconds{ static_cast<int>(get_node()->get_parameter("cmd_vel_timeout_seconds").as_double() * 1000.0)}; use_stamped_vel_ = get_node()->get_parameter("use_stamped_vel").as_bool(); // Run reset to make sure everything is initialized correctly if (!reset()) { return controller_interface::CallbackReturn::ERROR; } const Twist empty_twist; received_velocity_msg_ptr_.set(std::make_shared<Twist>(empty_twist)); previous_commands_.emplace(empty_twist); previous_commands_.emplace(empty_twist); // initialize command subscriber if (use_stamped_vel_) { velocity_command_subscriber_ = get_node()->create_subscription<Twist>( DEFAULT_COMMAND_TOPIC, rclcpp::SystemDefaultsQoS(), [this](const std::shared_ptr<Twist> msg) -> void { if (!subscriber_is_active_) { RCLCPP_WARN(get_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( get_node()->get_logger(), "Received TwistStamped with zero timestamp, setting it to current " "time, this message will only be shown once"); msg->header.stamp = get_node()->get_clock()->now(); } received_velocity_msg_ptr_.set(std::move(msg)); }); } else { velocity_command_unstamped_subscriber_ = get_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(get_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 = get_node()->get_clock()->now(); }); } previous_update_timestamp_ = get_node()->get_clock()->now(); return controller_interface::CallbackReturn::SUCCESS; } controller_interface::CallbackReturn SwerveController::on_activate(const rclcpp_lifecycle::State &) { front_left_wheel_command_handle_ = get_wheel(front_left_wheel_joint_name_); front_right_wheel_command_handle_ = get_wheel(front_right_wheel_joint_name_); rear_left_wheel_command_handle_ = get_wheel(rear_left_wheel_joint_name_); rear_right_wheel_command_handle_ = get_wheel(rear_right_wheel_joint_name_); front_left_axle_command_handle_ = get_axle(front_left_axle_joint_name_); front_right_axle_command_handle_ = get_axle(front_right_axle_joint_name_); rear_left_axle_command_handle_ = get_axle(rear_left_axle_joint_name_); rear_right_axle_command_handle_ = get_axle(rear_right_axle_joint_name_); if (!front_left_wheel_command_handle_ || !front_right_wheel_command_handle_ || !rear_left_wheel_command_handle_ || !rear_right_wheel_command_handle_ || !front_left_axle_command_handle_ || !front_right_axle_command_handle_ || !rear_left_axle_command_handle_ || !rear_right_axle_command_handle_) { return controller_interface::CallbackReturn::ERROR; } is_halted = false; subscriber_is_active_ = true; RCLCPP_DEBUG(get_node()->get_logger(), "Subscriber and publisher are now active."); return controller_interface::CallbackReturn::SUCCESS; } controller_interface::CallbackReturn SwerveController::on_deactivate(const rclcpp_lifecycle::State &) { subscriber_is_active_ = false; return controller_interface::CallbackReturn::SUCCESS; } controller_interface::CallbackReturn SwerveController::on_cleanup(const rclcpp_lifecycle::State &) { if (!reset()) { return controller_interface::CallbackReturn::ERROR; } received_velocity_msg_ptr_.set(std::make_shared<Twist>()); return controller_interface::CallbackReturn::SUCCESS; } controller_interface::CallbackReturn SwerveController::on_error(const rclcpp_lifecycle::State &) { if (!reset()) { return controller_interface::CallbackReturn::ERROR; } return controller_interface::CallbackReturn::SUCCESS; } bool SwerveController::reset() { subscriber_is_active_ = false; velocity_command_subscriber_.reset(); velocity_command_unstamped_subscriber_.reset(); std::queue<Twist> empty; std::swap(previous_commands_, empty); received_velocity_msg_ptr_.set(nullptr); is_halted = false; return true; } controller_interface::CallbackReturn SwerveController::on_shutdown(const rclcpp_lifecycle::State &) { return controller_interface::CallbackReturn::SUCCESS; } void SwerveController::halt() { front_left_wheel_command_handle_->set_velocity(0.0); front_right_wheel_command_handle_->set_velocity(0.0); rear_left_wheel_command_handle_->set_velocity(0.0); rear_right_wheel_command_handle_->set_velocity(0.0); auto logger = get_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 = get_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 + "/velocity" && 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; } auto cmd_interface_name = command_handle->get_name(); RCLCPP_INFO(logger, "FOUND! wheel cmd interface %s", cmd_interface_name.c_str()); 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 = get_node()->get_logger(); if (axle_name.empty()) { RCLCPP_ERROR(logger, "Axle joint name not given. Make sure all joints are specified."); return nullptr; } // Get Command Handle for joint const auto command_handle_position = std::find_if( command_interfaces_.begin(), command_interfaces_.end(), [&axle_name](const auto &interface) { return interface.get_name() == axle_name + "/position" && interface.get_interface_name() == HW_IF_POSITION; }); const auto state_handle = std::find_if( state_interfaces_.cbegin(), state_interfaces_.cend(), [&axle_name](const auto &interface) { return interface.get_name() == axle_name + "/position" && interface.get_interface_name() == HW_IF_POSITION; }); if (command_handle_position == command_interfaces_.end()) { RCLCPP_ERROR(logger, "Unable to obtain joint command handle for %s", axle_name.c_str()); return nullptr; } if (state_handle == state_interfaces_.cend()) { RCLCPP_ERROR(logger, "Unable to obtain joint state handle for %s", axle_name.c_str()); return nullptr; } auto cmd_interface_name = command_handle_position->get_name(); RCLCPP_INFO(logger, "FOUND! axle cmd interface %s", cmd_interface_name.c_str()); return std::make_shared<Axle>(std::ref(*command_handle_position), std::ref(*state_handle), axle_name); } } // namespace swerve_controller #include "class_loader/register_macro.hpp" CLASS_LOADER_REGISTER_CLASS( swerve_controller::SwerveController, controller_interface::ControllerInterface)
28,957
C++
43.896124
299
0.668267
RoboEagles4828/rift2024/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 "swerve_controller/speed_limiter.hpp" #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 { 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> command_position_,std::reference_wrapper< const hardware_interface::LoanedStateInterface> state_position_, std::string name); void set_position(double command_position_); double get_position (void); private: std::reference_wrapper<hardware_interface::LoanedCommandInterface> command_position_; std::reference_wrapper<const hardware_interface::LoanedStateInterface> state_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 controller_interface::CallbackReturn on_init() override; SWERVE_CONTROLLER_PUBLIC controller_interface::CallbackReturn on_configure(const rclcpp_lifecycle::State & previous_state) override; SWERVE_CONTROLLER_PUBLIC controller_interface::CallbackReturn on_activate(const rclcpp_lifecycle::State & previous_state) override; SWERVE_CONTROLLER_PUBLIC controller_interface::CallbackReturn on_deactivate(const rclcpp_lifecycle::State & previous_state) override; SWERVE_CONTROLLER_PUBLIC controller_interface::CallbackReturn on_cleanup(const rclcpp_lifecycle::State & previous_state) override; SWERVE_CONTROLLER_PUBLIC controller_interface::CallbackReturn on_error(const rclcpp_lifecycle::State & previous_state) override; SWERVE_CONTROLLER_PUBLIC controller_interface::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_wheel_command_handle_; std::shared_ptr<Wheel> front_right_wheel_command_handle_; std::shared_ptr<Wheel> rear_left_wheel_command_handle_; std::shared_ptr<Wheel> rear_right_wheel_command_handle_; std::shared_ptr<Axle> front_left_axle_command_handle_; std::shared_ptr<Axle> front_right_axle_command_handle_; std::shared_ptr<Axle> rear_left_axle_command_handle_; std::shared_ptr<Axle> rear_right_axle_command_handle_; 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_; // std::vector<double> last_wheel_commands{0.0,0.0,0.0,0.0}; // std::vector<double> second_last_wheel_commands{0.0,0.0,0.0,0.0}; SpeedLimiter limiter_linear_X_; SpeedLimiter limiter_linear_Y_; SpeedLimiter limiter_angular_Z_; std::queue<Twist> previous_commands_; 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_milliseconds_{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}; double max_wheel_angular_velocity_ = 0.0; bool is_halted = false; bool use_stamped_vel_ = true; bool reset(); void halt(); }; } // namespace swerve_controllerS #endif // Swerve_CONTROLLER__SWERVE_CONTROLLER_HPP_
5,964
C++
36.049689
182
0.753521
RoboEagles4828/rift2024/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/rift2024/src/swerve_controller/include/swerve_controller/speed_limiter.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: Enrique Fernández */ #ifndef SWERVE_CONTROLLER__SPEED_LIMITER_HPP_ #define SWERVE_CONTROLLER__SPEED_LIMITER_HPP_ #include <cmath> namespace swerve_controller { class SpeedLimiter { public: /** * \brief Constructor * \param [in] has_velocity_limits if true, applies velocity limits * \param [in] has_acceleration_limits if true, applies acceleration limits * \param [in] has_jerk_limits if true, applies jerk limits * \param [in] min_velocity Minimum velocity [m/s], usually <= 0 * \param [in] max_velocity Maximum velocity [m/s], usually >= 0 * \param [in] min_acceleration Minimum acceleration [m/s^2], usually <= 0 * \param [in] max_acceleration Maximum acceleration [m/s^2], usually >= 0 * \param [in] min_jerk Minimum jerk [m/s^3], usually <= 0 * \param [in] max_jerk Maximum jerk [m/s^3], usually >= 0 */ SpeedLimiter( bool has_velocity_limits = false, bool has_acceleration_limits = false, bool has_jerk_limits = false, double min_velocity = NAN, double max_velocity = NAN, double min_acceleration = NAN, double max_acceleration = NAN, double min_jerk = NAN, double max_jerk = NAN); /** * \brief Limit the velocity and acceleration * \param [in, out] v Velocity [m/s] * \param [in] v0 Previous velocity to v [m/s] * \param [in] v1 Previous velocity to v0 [m/s] * \param [in] dt Time step [s] * \return Limiting factor (1.0 if none) */ double limit(double & v, double v0, double v1, double dt); /** * \brief Limit the velocity * \param [in, out] v Velocity [m/s] * \return Limiting factor (1.0 if none) */ double limit_velocity(double & v); /** * \brief Limit the acceleration * \param [in, out] v Velocity [m/s] * \param [in] v0 Previous velocity [m/s] * \param [in] dt Time step [s] * \return Limiting factor (1.0 if none) */ double limit_acceleration(double & v, double v0, double dt); /** * \brief Limit the jerk * \param [in, out] v Velocity [m/s] * \param [in] v0 Previous velocity to v [m/s] * \param [in] v1 Previous velocity to v0 [m/s] * \param [in] dt Time step [s] * \return Limiting factor (1.0 if none) * \see http://en.wikipedia.org/wiki/Jerk_%28physics%29#Motion_control */ double limit_jerk(double & v, double v0, double v1, double dt); // Enable/Disable velocity/acceleration/jerk limits: bool has_velocity_limits_; bool has_acceleration_limits_; bool has_jerk_limits_; // Velocity limits: double min_velocity_; double max_velocity_; // Acceleration limits: double min_acceleration_; double max_acceleration_; // Jerk limits: double min_jerk_; double max_jerk_; }; } // namespace swerve_controller #endif // SWERVE_CONTROLLER__SPEED_LIMITER_HPP_
3,423
C++
31.609524
88
0.660532
RoboEagles4828/rift2024/src/zed_object_hardware_interface/setup.py
from setuptools import setup package_name = 'zed_object_hardware_interface' 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': [ 'zed_conversion = zed_object_hardware_interface.zed_conversion:main' ], }, )
721
Python
25.74074
80
0.617198
RoboEagles4828/rift2024/src/zed_object_hardware_interface/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/rift2024/src/zed_object_hardware_interface/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/rift2024/src/zed_object_hardware_interface/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/rift2024/src/zed_object_hardware_interface/zed_object_hardware_interface/zed_conversion.py
import rclpy from rclpy.node import Node from std_msgs.msg import String from zed_interfaces.msg import ObjectsStamped class ZedConversion(Node): def __init__(self): super().__init__('zed_conversion') self.zed_objects_subscriber = self.create_subscription(ObjectsStamped, '/real/zed/obj_det/objects', self.zed_objects_callback, 10) self.pose_publisher = self.create_publisher(String, '/real/obj_det_pose', 10) self.OKGREEN = '\033[92m' self.ENDC = '\033[0m' self.pose = String() self.get_logger().info(self.OKGREEN + "Configured and Activated Zed Conversion" + self.ENDC) def zed_objects_callback(self, objects: ObjectsStamped): if objects == None: self.get_logger().warn("Objects message recieved was null") else: if len(objects.objects) <= 0: self.get_logger().warn("NO OBJECTS DETECTED") empty = String() empty.data = "0.0|0.0|0.0" self.pose_publisher.publish(empty) else: x = objects.objects[0].position[0] y = objects.objects[0].position[1] z = objects.objects[0].position[2] self.pose.data = f"{float(x)}|{float(y)}|{float(z)}" print(self.pose) self.pose_publisher.publish(self.pose) def main(args=None): rclpy.init(args=args) zed_conversion = ZedConversion() rclpy.spin(zed_conversion) zed_conversion.destroy_node() rclpy.shutdown() if __name__ == '__main__': main()
1,638
Python
34.630434
138
0.571429
RoboEagles4828/rift2024/src/rift_bringup/launch/teleopLayer.launch.py
import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.actions import RegisterEventHandler, DeclareLaunchArgument from launch.substitutions import LaunchConfiguration, Command, PythonExpression from launch_ros.actions import Node from launch.conditions import IfCondition # Easy use of namespace since args are not strings # NAMESPACE = os.environ.get('ROS_NAMESPACE') if 'ROS_NAMESPACE' in os.environ else 'default' def generate_launch_description(): use_sim_time = LaunchConfiguration('use_sim_time') namespace = LaunchConfiguration('namespace') joystick_file = LaunchConfiguration('joystick_file') enable_joy = LaunchConfiguration('enable_joy') frc_auton_reader = Node( package = "frc_auton", namespace=namespace, executable= "reader", name = "frc_auton_node", parameters=[{ "auton_name": "24", }] ) frc_teleop_writer = Node( package = "frc_auton", namespace=namespace, executable= "writer", name = "frc_auton_node", parameters=[{ "record_auton": False, "record_without_fms": False, }] ) joy = Node( package='joy', namespace=namespace, executable='joy_node', name='joy_node', condition=IfCondition(enable_joy), parameters=[{ 'use_sim_time': use_sim_time, 'deadzone': 0.15, }]) controller_prefix = 'swerve_controller' joy_teleop_twist = Node( package='teleop_twist_joy', namespace=namespace, executable='teleop_node', name='teleop_twist_joy_node', parameters=[joystick_file, {'use_sim_time': use_sim_time}], remappings={ ("cmd_vel", f"{controller_prefix}/cmd_vel_unstamped"), ("odom", "zed/odom") }, ) joint_trajectory_teleop = Node( package='joint_trajectory_teleop', namespace=namespace, executable='joint_trajectory_teleop', name='joint_trajectory_teleop', parameters=[{'use_sim_time': use_sim_time}] ) # Launch! return LaunchDescription([ DeclareLaunchArgument( 'use_sim_time', default_value='false', description='Use sim time if true'), DeclareLaunchArgument( 'namespace', default_value='default', description='The namespace of nodes and links'), DeclareLaunchArgument( 'joystick_file', default_value='', description='The file with joystick parameters'), DeclareLaunchArgument( 'enable_joy', default_value='true', description='Enables joystick teleop'), joy, joy_teleop_twist, joint_trajectory_teleop, frc_auton_reader, # frc_teleop_writer ])
3,004
Python
32.021978
93
0.58988
RoboEagles4828/rift2024/src/rift_bringup/launch/rviz.launch.py
import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.actions import IncludeLaunchDescription from launch.launch_description_sources import PythonLaunchDescriptionSource NAMESPACE = os.environ.get('ROS_NAMESPACE') if 'ROS_NAMESPACE' in os.environ else 'default' def generate_launch_description(): bringup_path = get_package_share_directory("rift_bringup") rviz_file = os.path.join(bringup_path, 'config', 'description.rviz') common = { 'use_sim_time': 'false', 'namespace': NAMESPACE } control_launch_args = common | { 'use_ros2_control': 'false', 'load_controllers': 'false' } debug_launch_args = common | { 'enable_rviz': 'true', 'enable_foxglove': 'false', 'enable_joint_state_publisher': 'true', 'rviz_file': rviz_file } control_layer = IncludeLaunchDescription( PythonLaunchDescriptionSource([os.path.join( bringup_path,'launch','controlLayer.launch.py' )]), launch_arguments=control_launch_args.items()) debug_layer = IncludeLaunchDescription( PythonLaunchDescriptionSource([os.path.join( bringup_path,'launch','debugLayer.launch.py' )]), launch_arguments=debug_launch_args.items()) # Launch! return LaunchDescription([ # control_layer, debug_layer, ])
1,471
Python
34.902438
91
0.646499
RoboEagles4828/rift2024/src/rift_bringup/launch/isaac_pysim.launch.py
import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.actions import IncludeLaunchDescription, TimerAction from launch.launch_description_sources import PythonLaunchDescriptionSource from launch_ros.actions import Node NAMESPACE = os.environ.get('ROS_NAMESPACE') if 'ROS_NAMESPACE' in os.environ else 'default' def generate_launch_description(): bringup_path = get_package_share_directory("rift_bringup") rviz_file = os.path.join(bringup_path, 'config', 'view.rviz') common = { 'use_sim_time': 'true', 'namespace': NAMESPACE } debug_launch_args = common | { 'enable_rviz': 'false', 'enable_foxglove': 'false', 'rviz_file': rviz_file } joint_state_broadcaster_spawner = Node( package="controller_manager", namespace=NAMESPACE, executable="spawner", arguments=["joint_state_broadcaster", "-c", ['/', NAMESPACE, "/controller_manager"]], ) isaac_hadware_test = Node( package='isaac_hardware_test', namespace=NAMESPACE, executable='isaac_drive', parameters=[{}], ) debug_layer = IncludeLaunchDescription( PythonLaunchDescriptionSource([os.path.join( bringup_path,'launch','debugLayer.launch.py' )]), launch_arguments=debug_launch_args.items()) delay_debug_layer = TimerAction(period=3.0, actions=[debug_layer]) # Launch! return LaunchDescription([ # joint_state_broadcaster_spawner, isaac_hadware_test, delay_debug_layer, ])
1,642
Python
33.229166
93
0.653471
RoboEagles4828/rift2024/src/rift_bringup/launch/isaac-vslam.launch.py
import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.actions import IncludeLaunchDescription, TimerAction from launch.launch_description_sources import PythonLaunchDescriptionSource NAMESPACE = os.environ.get('ROS_NAMESPACE') if 'ROS_NAMESPACE' in os.environ else 'default' def generate_launch_description(): bringup_path = get_package_share_directory("rift_bringup") joystick_file = os.path.join(bringup_path, 'config', 'xbox-sim.yaml') rviz_file = os.path.join(bringup_path, 'config', 'view.rviz') common = { 'use_sim_time': 'true', 'namespace': NAMESPACE } isaac_layer = IncludeLaunchDescription( PythonLaunchDescriptionSource([os.path.join( bringup_path,'launch','isaac.launch.py' )])) rtab_layer = IncludeLaunchDescription( PythonLaunchDescriptionSource([os.path.join( bringup_path,'launch','rtab.launch.py' )])) delay_rtab_layer = TimerAction(period=8.0, actions=[rtab_layer]) pysim_layer = IncludeLaunchDescription( PythonLaunchDescriptionSource([os.path.join( bringup_path,'launch','isaac_pysim.launch.py' )])) rviz = IncludeLaunchDescription( PythonLaunchDescriptionSource([os.path.join( bringup_path,'launch','rviz.launch.py' )])) # Launch! return LaunchDescription([ isaac_layer, pysim_layer, # rviz, delay_rtab_layer, ])
1,592
Python
34.399999
91
0.643216
RoboEagles4828/rift2024/src/rift_bringup/launch/test_hw.launch.py
import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.actions import IncludeLaunchDescription, TimerAction from launch.launch_description_sources import PythonLaunchDescriptionSource NAMESPACE = os.environ.get('ROS_NAMESPACE') if 'ROS_NAMESPACE' in os.environ else 'default' def generate_launch_description(): bringup_path = get_package_share_directory("rift_bringup") joystick_file = os.path.join(bringup_path, 'config', 'xbox-sim.yaml') rviz_file = os.path.join(bringup_path, 'config', 'view.rviz') common = { 'use_sim_time': 'false', 'namespace': NAMESPACE } control_launch_args = common | { 'use_ros2_control': 'true', 'hardware_plugin': 'swerve_hardware/TestDriveHardware', } teleoplaunch_args = common | { 'joystick_file': joystick_file, } debug_launch_args = common | { 'enable_rviz': 'true', 'enable_foxglove': 'true', 'rviz_file': rviz_file } control_layer = IncludeLaunchDescription( PythonLaunchDescriptionSource([os.path.join( bringup_path,'launch','controlLayer.launch.py' )]), launch_arguments=control_launch_args.items()) teleop_layer = IncludeLaunchDescription( PythonLaunchDescriptionSource([os.path.join( bringup_path,'launch','teleopLayer.launch.py' )]), launch_arguments=teleoplaunch_args.items()) debug_layer = IncludeLaunchDescription( PythonLaunchDescriptionSource([os.path.join( bringup_path,'launch','debugLayer.launch.py' )]), launch_arguments=debug_launch_args.items()) delay_debug_layer = TimerAction(period=3.0, actions=[debug_layer]) # Launch! return LaunchDescription([ control_layer, teleop_layer, delay_debug_layer, ])
1,956
Python
35.924528
91
0.643149
RoboEagles4828/rift2024/src/rift_bringup/launch/zed2i.launch.py
import os from launch import LaunchDescription from launch.actions import IncludeLaunchDescription, TimerAction from launch.launch_description_sources import PythonLaunchDescriptionSource from ament_index_python.packages import get_package_share_directory from launch_ros.actions import Node # NAMESPACE = os.environ.get('ROS_NAMESPACE') if 'ROS_NAMESPACE' in os.environ else 'default' NAMESPACE = 'real' def generate_launch_description(): # Camera model (force value) camera_model = 'zed2i' config_common_path = os.path.join( get_package_share_directory('zed_wrapper'), 'config', 'common.yaml' ) config_camera_path = os.path.join( get_package_share_directory('zed_wrapper'), 'config', camera_model + '.yaml' ) # ZED Wrapper node zed_wrapper_node = Node( package='zed_wrapper', namespace=str(NAMESPACE), executable='zed_wrapper', name='zed', output='screen', #prefix=['xterm -e valgrind --tools=callgrind'], #prefix=['xterm -e gdb -ex run --args'], parameters=[ # YAML files config_common_path, # Common parameters config_camera_path, # Camera related parameters # Overriding { 'general.camera_name': f'{NAMESPACE}/{camera_model}', 'general.camera_model': camera_model, 'general.grab_resolution': 'SVGA', # 'general.svo_file': 'live', 'publish_urdf': 'false', 'pos_tracking.base_frame': f'{NAMESPACE}/base_link', 'pos_tracking.map_frame': f'{NAMESPACE}/map', 'pos_tracking.odometry_frame': f'{NAMESPACE}/odom', 'general.zed_id': 0, 'general.serial_number': 0, 'pos_tracking.publish_tf': True, 'pos_tracking.publish_map_tf': True, 'pos_tracking.publish_imu_tf': True } ] ) delay_zed_wrapper = TimerAction(period=5.0, actions=[zed_wrapper_node]) # Define LaunchDescription variable ld = LaunchDescription() # Add nodes to LaunchDescription ld.add_action(delay_zed_wrapper) return ld
2,264
Python
31.357142
93
0.590989
RoboEagles4828/rift2024/src/rift_bringup/launch/gym.launch.py
import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.actions import RegisterEventHandler, DeclareLaunchArgument from launch.substitutions import LaunchConfiguration, Command, PythonExpression from launch_ros.actions import Node from launch.conditions import IfCondition # Easy use of namespace since args are not strings # NAMESPACE = os.environ.get('ROS_NAMESPACE') if 'ROS_NAMESPACE' in os.environ else 'default' def generate_launch_description(): use_sim_time = LaunchConfiguration('use_sim_time') policy = Node( package='policy_runner', executable='runner', name='policy_runner_node', parameters=[{ 'use_sim_time': use_sim_time, 'odom_topic': '/saranga/zed/odom', 'target_topic': '/real/obj_det_pose', }] ) # Launch! return LaunchDescription([ DeclareLaunchArgument( 'use_sim_time', default_value='false', description='Use sim time if true'), policy ])
1,094
Python
32.181817
93
0.667276
RoboEagles4828/rift2024/src/rift_bringup/launch/controlLayer.launch.py
import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.actions import RegisterEventHandler, DeclareLaunchArgument, SetEnvironmentVariable, LogInfo, EmitEvent from launch.substitutions import LaunchConfiguration, Command, PythonExpression, TextSubstitution from launch.event_handlers import OnProcessExit from launch_ros.actions import Node from launch.conditions import IfCondition from launch.events import Shutdown # Easy use of namespace since args are not strings # NAMESPACE = os.environ.get('ROS_NAMESPACE') if 'ROS_NAMESPACE' in os.environ else 'default' def generate_launch_description(): use_sim_time = LaunchConfiguration('use_sim_time') use_ros2_control = LaunchConfiguration('use_ros2_control') load_controllers = LaunchConfiguration('load_controllers') forward_command_controllers = LaunchConfiguration('forward_command_controller') namespace = LaunchConfiguration('namespace') hardware_plugin = LaunchConfiguration('hardware_plugin') # Process the URDF file description_pkg_path = os.path.join(get_package_share_directory('rift_description')) xacro_file = os.path.join(description_pkg_path,'urdf', 'robots','rift.urdf.xacro') rift_description_xml = Command(['xacro ', xacro_file, ' hw_interface_plugin:=', hardware_plugin]) # Get paths to other config files bringup_pkg_path = os.path.join(get_package_share_directory('rift_bringup')) controllers_file = os.path.join(bringup_pkg_path, 'config', 'controllers.yaml') # Create a robot_state_publisher node node_robot_state_publisher = Node( package='robot_state_publisher', namespace=namespace, executable='robot_state_publisher', output='screen', parameters=[{ 'robot_description': rift_description_xml, 'use_sim_time': use_sim_time, 'publish_frequency': 50.0, 'frame_prefix': [namespace, '/'] }], ) # Starts ROS2 Control control_node = Node( package="controller_manager", namespace=namespace, executable="ros2_control_node", condition=IfCondition(use_ros2_control), parameters=[{ "robot_description": rift_description_xml, "use_sim_time": use_sim_time, }, controllers_file], output="both", ) control_node_require = RegisterEventHandler( event_handler=OnProcessExit( target_action=control_node, on_exit=[ LogInfo(msg="Listener exited; tearing down entire system."), EmitEvent(event=Shutdown()) ], ) ) # Starts ROS2 Control Joint State Broadcaster joint_state_broadcaster_spawner = Node( package="controller_manager", namespace=namespace, executable="spawner", arguments=["joint_state_broadcaster", "-c", ['/', namespace, "/controller_manager"]], condition=IfCondition(use_ros2_control), ) joint_trajectory_controller_spawner = Node( package="controller_manager", namespace=namespace, executable="spawner", arguments=["joint_trajectory_controller", "-c", ['/', namespace, "/controller_manager"]], parameters=[{ "robot_description": rift_description_xml, "use_sim_time": use_sim_time, }, controllers_file], condition=IfCondition(use_ros2_control and load_controllers), ) #Starts ROS2 Control Swerve Drive Controller swerve_drive_controller_spawner = Node( package="controller_manager", namespace=namespace, executable="spawner", arguments=["swerve_controller", "-c", ['/', namespace, "/controller_manager"]], condition=IfCondition(use_ros2_control and load_controllers), ) swerve_drive_controller_delay = RegisterEventHandler( event_handler=OnProcessExit( target_action=joint_state_broadcaster_spawner, on_exit=[swerve_drive_controller_spawner], ) ) # Starts ROS2 Control Forward Controller forward_position_controller_spawner = Node( package="controller_manager", namespace=namespace, executable="spawner", arguments=["forward_position_controller", "-c", ['/', namespace, "/controller_manager"]], condition=IfCondition(use_ros2_control and forward_command_controllers), ) forward_position_controller_delay = RegisterEventHandler( event_handler=OnProcessExit( target_action=joint_state_broadcaster_spawner, on_exit=[forward_position_controller_spawner], ) ) forward_velocity_controller_spawner = Node( package="controller_manager", namespace=namespace, executable="spawner", arguments=["forward_velocity_controller", "-c", ['/', namespace, "/controller_manager"]], condition=IfCondition(use_ros2_control and forward_command_controllers), ) forward_velocity_controller_delay = RegisterEventHandler( event_handler=OnProcessExit( target_action=joint_state_broadcaster_spawner, on_exit=[forward_velocity_controller_spawner], ) ) zed_object_conversion_node = Node( package='zed_object_hardware_interface', executable='zed_conversion', name='zed_object_conversion', output='screen', parameters=[{}] ) # Launch! return LaunchDescription([ SetEnvironmentVariable('RCUTILS_COLORIZED_OUTPUT', '1'), DeclareLaunchArgument( 'use_sim_time', default_value='false', description='Use sim time if true'), DeclareLaunchArgument( 'use_ros2_control', default_value='true', description='Use ros2_control if true'), DeclareLaunchArgument( 'namespace', default_value='default', description='The namespace of nodes and links'), DeclareLaunchArgument( 'hardware_plugin', default_value='swerve_hardware/IsaacDriveHardware', description='Which ros2 control hardware plugin to use'), DeclareLaunchArgument( 'load_controllers', default_value='true', description='Enable or disable ros2 controllers but leave hardware interfaces'), DeclareLaunchArgument( 'forward_command_controller', default_value='false', description='Forward commands for ros2 control'), node_robot_state_publisher, control_node, joint_state_broadcaster_spawner, joint_trajectory_controller_spawner, swerve_drive_controller_delay, forward_position_controller_delay, forward_velocity_controller_delay, control_node_require, zed_object_conversion_node ])
6,942
Python
38.225988
114
0.650101
RoboEagles4828/rift2024/src/rift_bringup/launch/rtab.launch.py
import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.actions import IncludeLaunchDescription, DeclareLaunchArgument from launch.launch_description_sources import PythonLaunchDescriptionSource from launch.substitutions import LaunchConfiguration NAMESPACE = os.environ.get('ROS_NAMESPACE') if 'ROS_NAMESPACE' in os.environ else 'default' def generate_launch_description(): use_sim_time = LaunchConfiguration('use_sim_time') rtabmap_ros_path = get_package_share_directory("rtabmap_launch") rtabmap_args = { 'rtabmap_args': '--delete_db_on_start', 'use_sim_time': use_sim_time, # Frames 'frame_id': f'{NAMESPACE}/base_link', # 'odom_frame_id': f'{NAMESPACE}/zed/odom', 'map_frame_id': f'{NAMESPACE}/map', # Topics 'rgb_topic': f'/{NAMESPACE}/left/rgb', 'camera_info_topic': f'/{NAMESPACE}/left/camera_info', 'depth_topic': f'/{NAMESPACE}/left/depth', 'imu_topic': f'/{NAMESPACE}/imu', # 'odom_topic': f'/{NAMESPACE}/zed/odom', 'approx_sync': 'false', 'wait_imu_to_init': 'true', # 'visual_odometry': 'false', # 'publish_tf_odom': 'false', 'qos': '1', 'rviz': 'true', } rtab_layer = IncludeLaunchDescription( PythonLaunchDescriptionSource([os.path.join( rtabmap_ros_path,'launch','rtabmap.launch.py' )]), launch_arguments=rtabmap_args.items()) return LaunchDescription([ DeclareLaunchArgument( 'use_sim_time', default_value='true', description='Use sim time if true'), rtab_layer, ])
1,741
Python
34.55102
91
0.620908
RoboEagles4828/rift2024/src/rift_bringup/launch/isaac.launch.py
import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.actions import IncludeLaunchDescription, TimerAction from launch.launch_description_sources import PythonLaunchDescriptionSource NAMESPACE = os.environ.get('ROS_NAMESPACE') if 'ROS_NAMESPACE' in os.environ else 'default' def generate_launch_description(): bringup_path = get_package_share_directory("rift_bringup") joystick_file = os.path.join(bringup_path, 'config', 'xbox-sim.yaml') rviz_file = os.path.join(bringup_path, 'config', 'view.rviz') common = { 'use_sim_time': 'true', 'namespace': NAMESPACE } control_launch_args = common | { 'use_ros2_control': 'true', 'hardware_plugin': 'swerve_hardware/IsaacDriveHardware', } teleoplaunch_args = common | { 'joystick_file': joystick_file, } debug_launch_args = common | { 'enable_rviz': 'true', 'enable_foxglove': 'false', 'rviz_file': rviz_file } control_layer = IncludeLaunchDescription( PythonLaunchDescriptionSource([os.path.join( bringup_path,'launch','controlLayer.launch.py' )]), launch_arguments=control_launch_args.items()) teleop_layer = IncludeLaunchDescription( PythonLaunchDescriptionSource([os.path.join( bringup_path,'launch','teleopLayer.launch.py' )]), launch_arguments=teleoplaunch_args.items()) debug_layer = IncludeLaunchDescription( PythonLaunchDescriptionSource([os.path.join( bringup_path,'launch','debugLayer.launch.py' )]), launch_arguments=debug_launch_args.items()) delay_debug_layer = TimerAction(period=3.0, actions=[debug_layer]) # Launch! return LaunchDescription([ control_layer, teleop_layer, delay_debug_layer, ])
1,957
Python
35.943396
91
0.643332