file_path
stringlengths 20
202
| content
stringlengths 9
3.85M
| size
int64 9
3.85M
| lang
stringclasses 9
values | avg_line_length
float64 3.33
100
| max_line_length
int64 8
993
| alphanum_fraction
float64 0.26
0.93
|
---|---|---|---|---|---|---|
NVIDIA-AI-IOT/isaac_demo/README.md | # isaac_demo

A combined set of demo working with Isaac SIM on a workstation and Isaac ROS on a NVIDIA Jetson AGX Orin
## Hardware required
Workstation:
1. Internet connection
2. x86/64 machine
3. Install Ubuntu 20.04
4. NVIDIA Graphic card with RTX
5. Display
6. Keyboard and Mouse
NVIDIA Jetson:
1. NVIDIA Jetson AGX Orin
2. Jetpack 5.1.2
Tools:
1. Router
2. eth cables
## Setup hardware
Before to start check you have all requirements and connect the driver following this image

It is preferable to connect workstation and the NVIDIA Jetson AGX Orin with a lan cable and not use WiFi.
## Install
There are two steps to follow, Install FoxGlove and Install Isaac ROS
Follow:
* Install on Jetson
* Install on workstation
### Install on NVIDIA Jetson Orin
Install on your NVIDIA Jetson Orin [Jetpack 5+](https://developer.nvidia.com/embedded/jetpack)
After installation save IP address and hostname
#### Connect remotely
In this section you connect to your NVIDIA Jetson with a ssh connection, open a terminal an write
```console
ssh <IP or hostname.local>
```
where **IP** is the of NVIDIA Jetson or **hostname** is the hostname of your board.
If you are connected the output from the terminal is:

#### Install Isaac Demo
Clone this repository and move to repository folder
```console
git clone https://github.com/rbonghi/isaac_demo.git
cd isaac_demo
```
Add docker group to your user
```console
sudo usermod -aG docker $USER && newgrp docker
```
Set the default nvidia runtime
You're going to be building containers, you need to set Docker's `default-runtime` to `nvidia`, so that the NVCC compiler and GPU are available during `docker build` operations. Add `"default-runtime": "nvidia"` to your `/etc/docker/daemon.json` configuration file before attempting to build the containers:
``` json
{
"default-runtime": "nvidia",
"runtimes": {
"nvidia": {
"path": "nvidia-container-runtime",
"runtimeArgs": []
}
}
}
```
Then restart the Docker service, or reboot your system before proceeding:
```console
sudo systemctl restart docker
```
Run the installer
```console
./isaac_demo.sh
```
If everything is going well (need time before to be done) the terminal will show this output

### Install on workstation
In this first part, you install different software on your workstation.
* NVIDIA Isaac SIM
* Foxglove
* This repository
#### NVIDIA Isaac SIM
Follow the documentation on NVIDIA Isaac SIM [Workstation install](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/install_workstation.html)
1. Download the [Omniverse Launcher](https://www.nvidia.com/en-us/omniverse/)
2. [Install Omniverse Launcher](https://docs.omniverse.nvidia.com/prod_launcher/prod_launcher/installing_launcher.html)
3. Install [Cache](https://docs.omniverse.nvidia.com/prod_nucleus/prod_utilities/cache/installation/workstation.html) from the Omniverse Launcher
4. Install [Nucleus](https://docs.omniverse.nvidia.com/prod_nucleus/prod_nucleus/workstation/installation.html) from the Omniverse Launcher
Open Omniverse Launcher

Move to Library and choice "Omniverse Isaac SIM" and download the latest 2022.2 version

#### Foxglove on Desktop
Download the latest [foxglove](https://foxglove.dev/download) version for your desktop
```console
sudo apt install ./foxglove-studio-*.deb
sudo apt update
sudo apt install -y foxglove-studio
```
#### Isaac SIM and Isaac DEMO
Clone this repository and move to repository folder
```console
git clone https://github.com/rbonghi/isaac_demo.git
cd isaac_demo
```
Now follow the Run demo to start the simulation
## Run demo
From your workstation now you need to do two extra steps
### Start Isaac SIM
Start the NVIDIA Isaac SIM from script
Open a terminal on your workstation and write
```console
cd isaac_demo
./isaac_demo.sh
```
Now this script initialize and run NVIDIA Isaac SIM, after a while you see a new window with Isaac SIM running

After this step you can complete to run the demo on your NVIDIA Jetson.
### Run simulation on Jetson
If you close your terminal on the installation, you can reopen with:
```console
ssh <IP or hostname.local>
```
where **IP** is the of NVIDIA Jetson or **hostname** is the hostname of your board.
and run
```console
cd isaac_demo
./isaac_demo.sh
```
Wait this script run the docker terminal, like the image below

Now you can run the script below
```console
bash src/isaac_demo/scripts/run_in_docker.sh
```
if you are planning to use Foxglove please run the same script with option `--foxglove`
```console
bash src/isaac_demo/scripts/run_in_docker.sh --foxglove
```
Well done! Now the Isaac ROS is running on your Jetson
### Setup foxglove
1. Open foxglove
2. Set up **Open connection**

3. Select **Foxglove WebSocket** and **Open**

4. Write on **WebSocket URL**
```console
ws://<IP or hostname.local>:8765
```
where **IP** is the of NVIDIA Jetson or **hostname** is the hostname of your board.
5. Setup Layout
Press on "Import layout" icon and after on top press the button **Import layout**

Select the layout on: **isaac_demo/foxglove/Default.json**
6. Output running

You can drive the robot directly from the foxglove joystick
## Troubleshooting
If Isaac SIM on your workstation show this message

just wait! :-)
| 6,164 | Markdown | 23.271653 | 308 | 0.746918 |
NVIDIA-AI-IOT/isaac_demo/isaac_ros/src/isaac_demo/launch/carter-foxglove.launch.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
import os
import launch
from launch_ros.actions import ComposableNodeContainer, Node
from launch.actions import DeclareLaunchArgument
from launch.substitutions import LaunchConfiguration
from launch.actions import IncludeLaunchDescription
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch_ros.descriptions import ComposableNode
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import ExecuteProcess
LOCAL_PATH = "/workspaces/isaac_ros-dev"
def generate_launch_description():
pkg_description = get_package_share_directory('carter_description')
bringup_dir = get_package_share_directory('nvblox_examples_bringup')
pkg_isaac_demo = get_package_share_directory('isaac_demo')
use_sim_time = LaunchConfiguration('use_sim_time',
default='True')
# Bi3DNode parameters
featnet_engine_file_path = LaunchConfiguration('featnet_engine_file_path')
segnet_engine_file_path = LaunchConfiguration('segnet_engine_file_path')
max_disparity_values = LaunchConfiguration('max_disparity_values')
# FreespaceSegmentationNode parameters
f_x_ = LaunchConfiguration('f_x')
f_y_ = LaunchConfiguration('f_y')
grid_height = LaunchConfiguration('grid_height')
grid_width = LaunchConfiguration('grid_width')
grid_resolution = LaunchConfiguration('grid_resolution')
############# ROS2 DECLARATIONS #############
# Launch Arguments
run_rviz_arg = DeclareLaunchArgument(
'run_rviz', default_value='True',
description='Whether to start RVIZ')
use_sim_dec = DeclareLaunchArgument(
'use_sim_time',
default_value='True',
description='Use simulation (Omniverse Isaac Sim) clock if true')
featnet_engine_file_arg = DeclareLaunchArgument(
'featnet_engine_file_path',
default_value=f"{LOCAL_PATH}/bi3d/bi3dnet_featnet.plan",
description='The absolute path to the Bi3D Featnet TensorRT engine plan')
segnet_engine_file_arg = DeclareLaunchArgument(
'segnet_engine_file_path',
default_value=f"{LOCAL_PATH}/bi3d/bi3dnet_segnet.plan",
description='The absolute path to the Bi3D Segnet TensorRT engine plan')
max_disparity_values_arg = DeclareLaunchArgument(
'max_disparity_values',
default_value='10',
description='The maximum number of disparity values given for Bi3D inference')
f_x_arg = DeclareLaunchArgument(
'f_x',
default_value='1465.99853515625',
description='The number of pixels per distance unit in the x dimension')
f_y_arg = DeclareLaunchArgument(
'f_y',
default_value='1468.2335205078125',
description='The number of pixels per distance unit in the y dimension')
grid_height_arg = DeclareLaunchArgument(
'grid_height',
default_value='2000',
description='The desired height of the occupancy grid, in cells')
grid_width_arg = DeclareLaunchArgument(
'grid_width',
default_value='2000',
description='The desired width of the occupancy grid, in cells')
grid_resolution_arg = DeclareLaunchArgument(
'grid_resolution',
default_value='0.01',
description='The desired resolution of the occupancy grid, in m/cell')
############# ROS2 NODES #############
############# ISAAC ROS NODES ########
apriltag_node = ComposableNode(
name='apriltag',
package='isaac_ros_apriltag',
plugin='nvidia::isaac_ros::apriltag::AprilTagNode',
remappings=[('/image', '/front/stereo_camera/left/rgb'),
('/camera_info', '/front/stereo_camera/left/camera_info'),
],
parameters=[{'size': 0.32,
'max_tags': 64}],
)
visual_slam_node = ComposableNode(
name='visual_slam_node',
package='isaac_ros_visual_slam',
plugin='isaac_ros::visual_slam::VisualSlamNode',
remappings=[('stereo_camera/left/camera_info', '/front/stereo_camera/left/camera_info'),
('stereo_camera/right/camera_info', '/front/stereo_camera/right/camera_info'),
('stereo_camera/left/image', '/front/stereo_camera/left/rgb'),
('stereo_camera/right/image', '/front/stereo_camera/right/rgb'),
('visual_slam/tracking/odometry', '/odom'),
],
parameters=[{
# 'enable_rectified_pose': False,
'denoise_input_images': True,
'rectified_images': True,
'enable_debug_mode': False,
'enable_imu': False,
'debug_dump_path': '/tmp/elbrus',
'left_camera_frame': 'carter_camera_stereo_left',
'right_camera_frame': 'carter_camera_stereo_right',
'map_frame': 'map',
'fixed_frame': 'odom',
'odom_frame': 'odom',
'base_frame': 'base_link',
'current_smooth_frame': 'base_link_smooth',
'current_rectified_frame': 'base_link_rectified',
'enable_observations_view': True,
'enable_landmarks_view': True,
'enable_reading_slam_internals': True,
'enable_slam_visualization': True,
'enable_localization_n_mapping': True,
# 'publish_odom_to_base_tf': False,
'publish_map_to_odom_tf': False,
'use_sim_time': use_sim_time
}]
)
bi3d_node = ComposableNode(
name='bi3d_node',
package='isaac_ros_bi3d',
plugin='nvidia::isaac_ros::bi3d::Bi3DNode',
parameters=[{
'featnet_engine_file_path': featnet_engine_file_path,
'segnet_engine_file_path': segnet_engine_file_path,
'max_disparity_values': max_disparity_values,
'disparity_values': [3, 6, 9, 12, 15, 18, 21, 24, 27, 30],
'use_sim_time': use_sim_time}],
remappings=[('bi3d_node/bi3d_output', 'bi3d_mask'),
('left_image_bi3d', '/front/stereo_camera/left/rgb'),
('right_image_bi3d', '/front/stereo_camera/right/rgb')]
)
freespace_segmentation_node = ComposableNode(
name='freespace_segmentation_node',
package='isaac_ros_bi3d_freespace',
plugin='nvidia::isaac_ros::bi3d_freespace::FreespaceSegmentationNode',
parameters=[{
'base_link_frame': 'base_link',
'camera_frame': 'carter_camera_stereo_left',
'f_x': f_x_,
'f_y': f_y_,
'grid_height': grid_height,
'grid_width': grid_width,
'grid_resolution': grid_resolution,
'use_sim_time': use_sim_time
}])
isaac_ros_launch_container = ComposableNodeContainer(
name='isaac_ros_launch_container',
namespace='',
package='rclcpp_components',
executable='component_container',
composable_node_descriptions=[
visual_slam_node,
apriltag_node,
bi3d_node,
freespace_segmentation_node,
],
output='screen'
)
############# OTHER ROS2 NODES #######
nav2_launch = IncludeLaunchDescription(
PythonLaunchDescriptionSource(os.path.join(
bringup_dir, 'launch', 'nav2', 'nav2_isaac_sim.launch.py')))
# Nvblox
nvblox_launch = IncludeLaunchDescription(
PythonLaunchDescriptionSource([
os.path.join(bringup_dir, 'launch', 'nvblox', 'nvblox.launch.py')]),
launch_arguments={'setup_for_isaac_sim': 'True'}.items())
# https://foxglove.dev/docs/studio/connection/ros2
# https://github.com/foxglove/ros-foxglove-bridge
foxglove_bridge_node = Node(
package='foxglove_bridge',
executable='foxglove_bridge',
# output='screen'
)
# include another launch file in nanosaur namespace
# https://docs.ros.org/en/foxy/How-To-Guides/Launch-file-different-formats.html
description_launch = IncludeLaunchDescription(
PythonLaunchDescriptionSource([pkg_description, '/launch/description.launch.py']),
)
############################
# Launch ROS2 packages
ld = LaunchDescription()
# Definitions
ld.add_action(use_sim_dec)
ld.add_action(featnet_engine_file_arg)
ld.add_action(segnet_engine_file_arg)
ld.add_action(max_disparity_values_arg)
ld.add_action(f_x_arg)
ld.add_action(f_y_arg)
ld.add_action(grid_height_arg)
ld.add_action(grid_width_arg)
ld.add_action(grid_resolution_arg)
# carter description launch
ld.add_action(description_launch)
# Foxglove
ld.add_action(foxglove_bridge_node)
# Isaac ROS container
ld.add_action(isaac_ros_launch_container)
# vSLAM and NVBLOX
ld.add_action(nvblox_launch)
# Navigation tool
ld.add_action(nav2_launch)
return ld
# EOF
| 10,105 | Python | 39.262948 | 98 | 0.636813 |
NVIDIA-AI-IOT/isaac_demo/isaac_ros/src/isaac_demo/scripts/carter_warehouse.py | # SPDX-FileCopyrightText: NVIDIA CORPORATION & AFFILIATES
# Copyright (c) 2021-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
import argparse
import time
from omni.isaac.kit import SimulationApp
def meters_to_stage_units(length_m: float) -> float:
from omni.isaac.core.utils.stage import get_stage_units
stage_units_in_meters = get_stage_units()
return length_m / stage_units_in_meters
def stage_units_to_camera_units(length_in_stage_units: float) -> float:
camera_lengths_in_stage_units = 1.0 / 10.0
return length_in_stage_units / camera_lengths_in_stage_units
def configure_lidar(carter_prim_path, controller):
# Lidar setup
carter_lidar_path = 'chassis_link/carter_lidar'
import omni
from pxr import Sdf
# Set up Lidar for a 32 layer like configuration
# omni.kit.commands.execute(
# 'ChangeProperty',
# prop_path=Sdf.Path(
# f'{carter_prim_path}/{carter_lidar_path}.highLod'),
# value=True,
# prev=None)
omni.kit.commands.execute(
'ChangeProperty',
prop_path=Sdf.Path(
f'{carter_prim_path}/{carter_lidar_path}.horizontalResolution'),
value=0.2,
prev=None,
)
omni.kit.commands.execute(
'ChangeProperty',
prop_path=Sdf.Path(
f'{carter_prim_path}/{carter_lidar_path}.minRange'),
value=0.7,
prev=None,
)
omni.kit.commands.execute(
'ChangeProperty',
prop_path=Sdf.Path(
f'{carter_prim_path}/{carter_lidar_path}.verticalFov'),
value=30.0,
prev=None,
)
omni.kit.commands.execute(
'ChangeProperty',
prop_path=Sdf.Path(
f'{carter_prim_path}/{carter_lidar_path}.verticalResolution'),
value=1.0,
prev=None,
)
# Disable publish odometry
# publish = controller.node(f'ros2_publish_odometry',
# f'{carter_prim_path}/ActionGraph')
# publish.delete_node()
# publish.get_attribute('inputs:execIn').set('')
# Create pcl reader node
read_pcl_node_path = f'{carter_prim_path}/ActionGraph/isaac_read_lidar_point_cloud_node'
read_pcl_node = controller.create_node(
read_pcl_node_path,
'omni.isaac.range_sensor.IsaacReadLidarPointCloud',
True,
)
# Add relationship to lidar prim
import omni.usd
stage = omni.usd.get_context().get_stage()
read_pcl_prim = stage.GetPrimAtPath(read_pcl_node_path)
input_rel = read_pcl_prim.GetRelationship('inputs:lidarPrim')
input_rel.SetTargets([f'{carter_prim_path}/{carter_lidar_path}'])
# Retrieve on playback node
playback_node = controller.node('on_playback_tick',
f'{carter_prim_path}/ActionGraph')
# Connect the tick to the lidar pcl read
controller.connect(playback_node.get_attribute('outputs:tick'),
read_pcl_node.get_attribute('inputs:execIn'))
# Create ros2 publisher node
publish_pcl_node = controller.create_node(
f'{carter_prim_path}/ActionGraph/ros2_publish_point_cloud',
'omni.isaac.ros2_bridge.ROS2PublishPointCloud', True)
# Set frame id
publish_pcl_node.get_attribute('inputs:frameId').set('carter_lidar')
# Connect pcl read to pcl publish
controller.connect(read_pcl_node.get_attribute('outputs:execOut'),
publish_pcl_node.get_attribute('inputs:execIn'))
controller.connect(read_pcl_node.get_attribute('outputs:pointCloudData'),
publish_pcl_node.get_attribute('inputs:pointCloudData'))
# Get timestamp node and connect it
timestamp_node = controller.node('isaac_read_simulation_time',
f'{carter_prim_path}/ActionGraph')
controller.connect(timestamp_node.get_attribute('outputs:simulationTime'),
publish_pcl_node.get_attribute('inputs:timeStamp'))
# Get context node and connect it
context_node = controller.node('ros2_context',
f'{carter_prim_path}/ActionGraph')
controller.connect(context_node.get_attribute('outputs:context'),
publish_pcl_node.get_attribute('inputs:context'))
# Get namespace node and connect it
namespace_node = controller.node('node_namespace',
f'{carter_prim_path}/ActionGraph')
controller.connect(namespace_node.get_attribute('inputs:value'),
publish_pcl_node.get_attribute('inputs:nodeNamespace'))
def configure_camera(carter_prim_path, controller, name):
# print(f"----------------------------- {name} -------------------------------------")
# Configure camera resolution
# Create camera node and set target resolution
resolution_node = controller.create_node(
f'{carter_prim_path}/ROS_Cameras/isaac_set_viewport_{name}_resolution',
'omni.isaac.core_nodes.IsaacSetViewportResolution',
True,
)
resolution_node.get_attribute('inputs:width').set(640)
resolution_node.get_attribute('inputs:height').set(480)
# Get viewport creation node
viewport_node = controller.node(f'isaac_create_viewport_{name}',
f'{carter_prim_path}/ROS_Cameras')
# Connect it
controller.connect(viewport_node.get_attribute('outputs:execOut'),
resolution_node.get_attribute('inputs:execIn'))
controller.connect(viewport_node.get_attribute('outputs:viewport'),
resolution_node.get_attribute('inputs:viewport'))
# Change publication topics
rgb = controller.node(f'ros2_create_camera_{name}_rgb',
f'{carter_prim_path}/ROS_Cameras')
rgb.get_attribute('inputs:topicName').set(f'/{name}/rgb')
info = controller.node(f'ros2_create_camera_{name}_info',
f'{carter_prim_path}/ROS_Cameras')
info.get_attribute('inputs:topicName').set(f'/{name}/camera_info')
depth = controller.node(f'ros2_create_camera_{name}_depth',
f'{carter_prim_path}/ROS_Cameras')
depth.get_attribute('inputs:topicName').set(f'/{name}/depth')
# Finally, enable rgb and depth
for enable_name in [
f'enable_camera_{name}', f'enable_camera_{name}_rgb',
f'enable_camera_{name}_depth'
]:
enable = controller.node(enable_name,
f'{carter_prim_path}/ROS_Cameras')
enable.get_attribute('inputs:condition').set(True)
return info
def setup_carter_sensors(carter_prim_path: str,
camera_focal_length_m: float = 0.009,
carter_version: int = 1,
enable_lidar: bool = True,
enable_odometry: bool = False):
# Set up variables based on carter version.
left_cam_path = 'chassis_link/camera_mount/carter_camera_stereo_left'
right_cam_path = 'chassis_link/camera_mount/carter_camera_stereo_right'
stereo_offset = [-175.92, 0]
if carter_version == 2:
left_cam_path = (
'chassis_link/stereo_cam_left/stereo_cam_left_sensor_frame/'
'camera_sensor_left')
right_cam_path = (
'chassis_link/stereo_cam_right/stereo_cam_right_sensor_frame/'
'camera_sensor_right')
stereo_offset = [-175.92, 0]
import omni
from pxr import Sdf
# Enable
# Change the focal length of the camera (default in the carter model quite narrow).
camera_focal_length_in_camera_units = stage_units_to_camera_units(
meters_to_stage_units(camera_focal_length_m))
omni.kit.commands.execute(
'ChangeProperty',
prop_path=Sdf.Path(f'{carter_prim_path}/{left_cam_path}.focalLength'),
value=camera_focal_length_in_camera_units,
prev=None)
omni.kit.commands.execute(
'ChangeProperty',
prop_path=Sdf.Path(f'{carter_prim_path}/{right_cam_path}.focalLength'),
value=camera_focal_length_in_camera_units,
prev=None)
# Modify the omnigraph to get lidar point cloud published
import omni.graph.core as og
keys = og.Controller.Keys
controller = og.Controller()
if not enable_odometry:
# Remove odometry from Carter
og.Controller.edit(f'{carter_prim_path}/ActionGraph',
{keys.DELETE_NODES: ['isaac_compute_odometry_node',
'ros2_publish_odometry',
'ros2_publish_raw_transform_tree',
# 'ros2_publish_transform_tree_01',
]})
if enable_lidar:
configure_lidar(carter_prim_path, controller)
else:
# Remove laser scan
og.Controller.edit(f'{carter_prim_path}/ActionGraph',
{keys.DELETE_NODES: ['isaac_read_lidar_beams_node', 'ros2_publish_laser_scan']})
# Configure left camera
configure_camera(carter_prim_path, controller, 'left')
# Configure right camera
right_info = configure_camera(carter_prim_path, controller, 'right')
# Set attribute
right_info.get_attribute('inputs:stereoOffset').set(stereo_offset)
def setup_forklifts_collision():
# Finally forklifts
import omni.kit.commands
from omni.isaac.core.utils.prims import is_prim_path_valid
from pxr import Sdf
for forklift_name in ['Forklift', 'Forklift_01']:
forklift_path = f'/World/warehouse_with_forklifts/{forklift_name}'
# Ignore if they do not exist
if not is_prim_path_valid(forklift_path):
continue
# Enable collision on main body
omni.kit.commands.execute(
'ChangeProperty',
prop_path=Sdf.Path(
f'{forklift_path}/S_ForkliftBody.physics:collisionEnabled'),
value=True,
prev=None,
)
# Disable collision on invible main body box
omni.kit.commands.execute(
'ChangeProperty',
prop_path=Sdf.Path(
f'{forklift_path}/chassis_collision.physics:collisionEnabled'),
value=False,
prev=None,
)
# Enable collision on tine
omni.kit.commands.execute(
'ChangeProperty',
prop_path=Sdf.Path(
f'{forklift_path}/S_ForkliftFork/collision_box.physics:collisionEnabled'
),
value=False,
prev=None,
)
# Disable collision on tine box
omni.kit.commands.execute(
'ChangeProperty',
prop_path=Sdf.Path(
f'{forklift_path}/S_ForkliftFork/S_ForkliftFork.physics:collisionEnabled'
),
value=True,
prev=None,
)
def main(scenario_path: str,
tick_rate_hz: float = 20.0,
headless: bool = False,
carter_prim_path: str = '/World/Carter_ROS',
carter_version: int = 1):
# Start up the simulator
simulation_app = SimulationApp({
'renderer': 'RayTracedLighting',
'headless': headless
})
import omni
from omni.isaac.core import SimulationContext
# enable ROS2 bridge extension
from omni.isaac.core.utils.extensions import enable_extension
enable_extension('omni.isaac.ros2_bridge')
from omni.isaac.core.utils.nucleus import get_assets_root_path
assets_root_path = get_assets_root_path()
if assets_root_path is None:
import carb
carb.log_error('Could not find Isaac Sim assets folder')
simulation_app.close()
exit()
usd_path = assets_root_path + scenario_path
print('------{0} n scenario_path:{1}', usd_path, scenario_path)
# Load the stage
omni.usd.get_context().open_stage(usd_path, None)
# Wait two frames so that stage starts loading
simulation_app.update()
simulation_app.update()
print('Loading stage...')
from omni.isaac.core.utils.stage import is_stage_loading
while is_stage_loading():
simulation_app.update()
print('Loading Complete')
time_dt = 1.0 / tick_rate_hz
print(f'Running sim at {tick_rate_hz} Hz, with dt of {time_dt}')
simulation_context = SimulationContext(stage_units_in_meters=1.0)
# Configure sensors
print(
f'Configuring sensors for Carter {carter_version} at: {carter_prim_path}'
)
setup_carter_sensors(carter_prim_path, carter_version=carter_version)
setup_forklifts_collision()
simulation_context.play()
simulation_context.step()
# Simulate for one second to warm up sim and let everything settle
# Otherwise the resizes below sometimes don't stick.
for frame in range(round(tick_rate_hz)):
simulation_context.step()
# Dock the second camera window
right_viewport = omni.ui.Workspace.get_window('Viewport')
left_viewport = omni.ui.Workspace.get_window('1') # Viewport 2
if right_viewport is not None and left_viewport is not None:
left_viewport.dock_in(right_viewport, omni.ui.DockPosition.LEFT)
right_viewport = None
left_viewport = None
# Run the sim
last_frame_time = time.monotonic()
while simulation_app.is_running():
simulation_context.step()
current_frame_time = time.monotonic()
if current_frame_time - last_frame_time < time_dt:
time.sleep(time_dt - (current_frame_time - last_frame_time))
last_frame_time = time.monotonic()
simulation_context.stop()
simulation_app.close()
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Sample app for running Carter in a Warehouse for NVblox.')
parser.add_argument(
'--scenario_path',
metavar='scenario_path',
type=str,
help='Path of the scenario to launch relative to the nucleus server '
'base path. Scenario must contain a carter robot.',
default='/Isaac/Samples/ROS2/Scenario/carter_warehouse_navigation.usd') # OLD /Isaac/Samples/ROS2/Scenario/carter_warehouse_navigation.usd - /Isaac/Samples/ROS2/Scenario/carter_warehouse_apriltags_worker.usd
parser.add_argument(
'--tick_rate_hz',
metavar='tick_rate_hz',
type=int,
help='The rate (in hz) that we step the simulation at.',
default=20)
parser.add_argument('--carter_prim_path',
metavar='carter_prim_path',
type=str,
default='/World/Carter_ROS',
help='Path to Carter.')
parser.add_argument('--headless', action='store_true')
parser.add_argument('--carter_version',
type=int,
default=1,
help='Version of the Carter robot (1 or 2)')
args, unknown = parser.parse_known_args()
main(args.scenario_path, args.tick_rate_hz, args.headless,
args.carter_prim_path, args.carter_version)
| 15,642 | Python | 37.624691 | 216 | 0.619997 |
NVIDIA-AI-IOT/isaac_demo/isaac_ros/src/isaac_demo/scripts/start_isaac_sim.py | # SPDX-FileCopyrightText: NVIDIA CORPORATION & AFFILIATES
# Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
import argparse
import os
import random
import time
import omni
ADDITIONAL_EXTENSIONS_BASE = ['omni.isaac.ros2_bridge-humble']
ADDITIONAL_EXTENSIONS_PEOPLE = [
'omni.anim.people', 'omni.anim.navigation.bundle', 'omni.anim.timeline',
'omni.anim.graph.bundle', 'omni.anim.graph.core', 'omni.anim.graph.ui',
'omni.anim.retarget.bundle', 'omni.anim.retarget.core',
'omni.anim.retarget.ui', 'omni.kit.scripting']
def enable_extensions_for_sim(with_people: bool = False):
"""
Enable the required extensions for the simulation.
Args:
with_people (bool, optional): Loads the human animation extensions if the scene with
humans is requested. Defaults to False.
"""
from omni.isaac.core.utils.extensions import enable_extension
add_exten = ADDITIONAL_EXTENSIONS_BASE
if with_people:
add_exten = ADDITIONAL_EXTENSIONS_BASE + ADDITIONAL_EXTENSIONS_PEOPLE
for idx in range(len(add_exten)):
enable_extension(add_exten[idx])
def rebuild_nav_mesh():
"""
Rebuild the navmesh with the correct settings. Used for the people to move around.
Called only when the sim with people is requested.
"""
# Navigation mesh rebake settings
import omni.kit.commands
print('Rebuilding navigation mesh...')
omni.kit.commands.execute(
'ChangeSetting',
path='/exts/omni.anim.navigation.core/navMesh/config/height',
value=1.5)
omni.kit.commands.execute(
'ChangeSetting',
path='/exts/omni.anim.navigation.core/navMesh/config/radius',
value=0.5)
omni.kit.commands.execute(
'ChangeSetting',
path='/exts/omni.anim.navigation.core/navMesh/config/maxSlope',
value=60.0)
omni.kit.commands.execute(
'ChangeSetting',
path='/exts/omni.anim.navigation.core/navMesh/config/maxClimb',
value=0.2)
omni.kit.commands.execute(
'ChangeSetting',
path='/persistent/exts/omni.anim.navigation.core/navMesh/autoRebakeDelaySeconds',
value=4)
omni.kit.commands.execute(
'ChangeSetting',
path='/persistent/exts/omni.anim.navigation.core/navMesh/viewNavMesh',
value=False)
print('Navigation mesh rebuilt.')
def create_people_commands(environment_prim_path: str,
anim_people_command_dir: str,
max_number_tries: int,
num_waypoints_per_human: int):
"""
Create the occupancy grid which returns the free points for the humans to move.
These points are then randomly sampled and assigned to each person and is saved as a txt file
which can be used as the command file for people animation. It directly gets the context of
the scene once the scene is opened and played in IsaacSim.
Args:
environment_prim_path (str): The warehouse enviroment prim path
anim_people_command_dir (str): The local directory to be used for storing the command file
max_number_tries (int): The number of times the script attempts to select a new waypoint
for a human.
num_waypoints_per_human (int): The number of waypoints to create per human.
"""
from omni.isaac.occupancy_map import _occupancy_map
import omni.anim.navigation.core as navcore
from omni.isaac.core.prims import XFormPrim
import carb
navigation_interface = navcore.acquire_interface()
print('Creating randomized paths for people...')
bounding_box = omni.usd.get_context().compute_path_world_bounding_box(
environment_prim_path)
physx = omni.physx.acquire_physx_interface()
stage_id = omni.usd.get_context().get_stage_id()
generator = _occupancy_map.Generator(physx, stage_id)
# 0.05m cell size, output buffer will have 0 for occupied cells, 1 for
# unoccupied, and 6 for cells that cannot be seen
# this assumes your usd stage units are in m, and not cm
generator.update_settings(.05, 0, 1, 6)
# Setting the transform for the generator
generator.set_transform(
# The starting location to map from
(0, 0, 0.025),
# The min bound
(bounding_box[0][0], bounding_box[0][1], 0.025),
# The max bound
(bounding_box[1][0], bounding_box[1][1], 0.025))
generator.generate2d()
# Get locations of free points
free_points = generator.get_free_positions()
# Find out number of humans in scene and create a list with their names
human_names = []
human_prims = []
for human in omni.usd.get_context().get_stage().GetPrimAtPath(
'/World/Humans').GetAllChildren():
human_name = human.GetChildren()[0].GetName()
# To remove biped setup prim from the list
if 'CharacterAnimation' in human_name or 'Biped_Setup' in human_name:
continue
human_names.append(human_name)
human_prims.append(XFormPrim(human.GetPath().pathString))
random_waypoints = {}
for human_name, human_prim in zip(human_names, human_prims):
# Get the human initial position.
start_point, _ = human_prim.get_world_pose()
# Initialize target waypoints.
random_waypoints[human_name] = []
for _ in range(num_waypoints_per_human):
current_tries = 0
path = None
# Sample for a maximum number of tries then give up.
while path is None and current_tries < max_number_tries:
new_waypoint = random.sample(free_points, 1)
# Check that a path exists between the starting position and the destination
path = navigation_interface.query_navmesh_path(
carb.Float3(start_point), new_waypoint[0])
current_tries += 1
if path is not None:
new_waypoint[0].z = 0.0
random_waypoints[human_name].append(new_waypoint[0])
print(
f'Found path for {human_name} from {start_point} to {new_waypoint[0]} after \
{current_tries} tries')
start_point = new_waypoint[0]
else:
print(
f'Could not find path for {human_name} after {max_number_tries}, skipping')
# Save as command file
command_file_path = os.path.join(
anim_people_command_dir, 'human_cmd_file.txt')
print(f'Saving randomized commands to {command_file_path}')
with open(command_file_path, 'w') as file:
for human_name, waypoints in random_waypoints.items():
human_command_line = f'{human_name} GoTo '
for next_waypoint in waypoints:
human_command_line += f'{next_waypoint[0]} {next_waypoint[1]} 0 '
human_command_line += '_\n'
file.write(human_command_line)
def update_people_command_file_path(anim_people_command_dir: str):
"""
Update the command file path settings in the simulation scene to the custom one.
Args:
anim_people_command_dir (str): The directory where the generated/custom command file is
stored.
"""
import omni.kit.commands
omni.kit.commands.execute(
'ChangeSetting',
path='/exts/omni.anim.people/command_settings/command_file_path',
value=anim_people_command_dir + '/human_cmd_file.txt')
def configure_camera(carter_prim_path, controller, name):
# print(f"----------------------------- {name} -------------------------------------")
# Change publication topics
rgb = controller.node(f'ros2_create_camera_{name}_rgb',
f'{carter_prim_path}/ROS_Cameras')
rgb.get_attribute('inputs:topicName').set(f'/front/stereo_camera/{name}/rgb')
info = controller.node(f'ros2_create_camera_{name}_info',
f'{carter_prim_path}/ROS_Cameras')
info.get_attribute('inputs:topicName').set(f'/front/stereo_camera/{name}/camera_info')
depth = controller.node(f'ros2_create_camera_{name}_depth',
f'{carter_prim_path}/ROS_Cameras')
depth.get_attribute('inputs:topicName').set(f'/front/stereo_camera/{name}/depth')
# Finally, enable rgb and depth
for enable_name in [
f'enable_camera_{name}', f'enable_camera_{name}_rgb',
f'enable_camera_{name}_depth'
]:
enable = controller.node(enable_name,
f'{carter_prim_path}/ROS_Cameras')
enable.get_attribute('inputs:condition').set(True)
return info
def main(scenario_path: str,
anim_people_command_dir: str,
environment_prim_path: str,
random_command_generation: bool,
num_waypoints: int,
headless: bool = False,
with_people: bool = True,
use_generated_command_file: bool = False,
tick_rate_hz: float = 60.0):
# Start up the simulator
from omni.isaac.kit import SimulationApp
simulation_app = SimulationApp({
'renderer': 'RayTracedLighting',
'headless': headless,
'width': 720,
'height': 480
})
import omni.kit.commands
from omni.isaac.core import SimulationContext
from omni.isaac.core.utils.nucleus import get_assets_root_path
# Enables the simulation extensions
enable_extensions_for_sim(with_people)
assets_root_path = get_assets_root_path()
print(f'##### [from omni.isaac.core.utils.nucleus] get_assets_root_path() returns: {assets_root_path}')
if assets_root_path is None:
print(
'Could not find Isaac Sim assets folder. Make sure you have an up to date local \
Nucleus server or that you have a proper connection to the internet.'
)
simulation_app.close()
exit()
usd_path = assets_root_path + scenario_path
print(f'Opening stage {usd_path}...')
# Load the stage
omni.usd.get_context().open_stage(usd_path, None)
# Wait two frames so that stage starts loading
simulation_app.update()
simulation_app.update()
print('Loading stage...')
from omni.isaac.core.utils.stage import is_stage_loading
while is_stage_loading():
simulation_app.update()
print('Loading Complete')
# If the scene with people is requested we build/rebuild the navmesh
# We also point to the generated/custom command file for people animation if set by user
if with_people:
rebuild_nav_mesh()
if not random_command_generation and use_generated_command_file:
update_people_command_file_path(anim_people_command_dir)
# Modify the omnigraph to get lidar point cloud published
import omni.graph.core as og
keys = og.Controller.Keys
controller = og.Controller()
enable_odometry = False
carter_prim_path = '/World/Carter_ROS'
if not enable_odometry:
# Remove odometry from Carter
og.Controller.edit(f'{carter_prim_path}/ActionGraph',
{keys.DELETE_NODES: ['isaac_compute_odometry_node',
'ros2_publish_odometry',
'ros2_publish_raw_transform_tree',
# 'ros2_publish_transform_tree_01',
]})
# Configure left camera
configure_camera(carter_prim_path, controller, 'left')
# Configure right camera
right_info = configure_camera(carter_prim_path, controller, 'right')
stereo_offset = [-175.92, 0]
# Set attribute
right_info.get_attribute('inputs:stereoOffset').set(stereo_offset)
time_dt = 1.0 / tick_rate_hz
print(f'### Running sim at {tick_rate_hz} Hz, with dt of {time_dt}')
# Run physics at 60 Hz and render time at the set frequency to see the sim as real time
simulation_context = SimulationContext(stage_units_in_meters=1.0,
physics_dt=1.0 / 60,
rendering_dt=time_dt)
simulation_context.play()
simulation_context.step()
# Physics can only be seen when the scene is played
# If we want to generate the command file for the people simulation we call the
# create_people_commands method, which stores the command file and then we close the
# simulation and point the user on how to use the generated file
if with_people and random_command_generation:
print('Creating human animation file...')
create_people_commands(environment_prim_path,
anim_people_command_dir, 10, num_waypoints)
print(
'Human command file has been created at {}/human_human_cmd_file.txt'
.format(anim_people_command_dir))
print(
'Please restart the simulation with --with_people and \n \
--use_generated_command_file to use the generated command file in human simulation'
)
simulation_context.stop()
simulation_app.close()
# Simulate for a few seconds to warm up sim and let everything settle
for _ in range(2*round(tick_rate_hz)):
simulation_context.step()
# Dock the second camera window
right_viewport = omni.ui.Workspace.get_window('Viewport')
left_viewport = omni.ui.Workspace.get_window('1') # Viewport 2
if right_viewport is not None and left_viewport is not None:
left_viewport.dock_in(right_viewport, omni.ui.DockPosition.LEFT)
right_viewport = None
left_viewport = None
# Run the sim
last_frame_time = time.monotonic()
while simulation_app.is_running():
simulation_context.step()
current_frame_time = time.monotonic()
if current_frame_time - last_frame_time < time_dt:
time.sleep(time_dt - (current_frame_time - last_frame_time))
last_frame_time = time.monotonic()
simulation_context.stop()
simulation_app.close()
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Sample app for running Carter in a Warehouse for NVblox.')
parser.add_argument(
'--scenario_path',
help='Path of the scenario to launch relative to the nucleus server '
'base path. Scenario must contain a carter robot. If the scene '
'contains animated humans, the script expects to find them under /World/Humans. '
'Example scenarios are /Isaac/Samples/NvBlox/carter_warehouse_navigation_with_people.usd '
'or /Isaac/Samples/NvBlox/carter_warehouse_navigation.usd',
#default='/Isaac/Samples/NvBlox/carter_warehouse_navigation.usd'
default='/Isaac/Samples/ROS2/Scenario/carter_warehouse_apriltags_worker.usd'
)
parser.add_argument('--environment_prim_path',
default='/World/WareHouse',
help='Path to the world to create a navigation mesh.')
parser.add_argument(
'--tick_rate_hz',
type=int,
help='The rate (in hz) that we step the simulation at.',
default=60)
parser.add_argument(
'--anim_people_waypoint_dir',
help='Directory location to save the waypoints in a yaml file')
parser.add_argument('--headless', action='store_true',
help='Run the simulation headless.')
parser.add_argument(
'--with_people',
help='If used, animation extensions for humans will be enabled.',
action='store_true')
parser.add_argument(
'--random_command_generation',
help='Choose whether we generate random waypoint or run sim',
action='store_true')
parser.add_argument('--num_waypoints', type=int,
help='Number of waypoints to generate for each human in the scene.',
default=5)
parser.add_argument(
'--use_generated_command_file',
help='Choose whether to use generated/custom command file or to use the default one to run\
the people animation',
action='store_true')
# This allows for IsaacSim options to be passed on the SimulationApp.
args, unknown = parser.parse_known_args()
# If we want to generate the command file then we run the simulation headless
if args.random_command_generation:
args.headless = True
# Check if the command file directory is given if it has to be generated or used for the
# simulation
if args.random_command_generation or args.use_generated_command_file:
if not args.anim_people_waypoint_dir:
raise ValueError(
'Input to command file directory required if custom command file has to be \
generated/used!!'
)
main(args.scenario_path, args.anim_people_waypoint_dir, args.environment_prim_path,
args.random_command_generation, args.num_waypoints, args.headless, args.with_people,
args.use_generated_command_file, args.tick_rate_hz)
| 17,704 | Python | 40.270396 | 108 | 0.635224 |
NVIDIA-AI-IOT/isaac_demo/isaac_ros/src/carter_description/launch/description.launch.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription, LaunchContext
from launch.substitutions import Command, LaunchConfiguration
from launch.actions import DeclareLaunchArgument, OpaqueFunction
from launch_ros.actions import Node
def generate_launch_description():
# URDF/xacro file to be loaded by the Robot State Publisher node
default_xacro_path = os.path.join(
get_package_share_directory('carter_description'),
'urdf',
'carter.urdf'
)
xacro_path = LaunchConfiguration('xacro_path')
declare_model_path_cmd = DeclareLaunchArgument(
name='xacro_path',
default_value=default_xacro_path,
description='Absolute path to robot urdf file')
robot_state_publisher_node = Node(
package='robot_state_publisher',
executable='robot_state_publisher',
parameters=[{
'robot_description': Command(
[
'xacro ', xacro_path, ' ',
])
}]
)
# Define LaunchDescription variable and return it
ld = LaunchDescription()
ld.add_action(declare_model_path_cmd)
ld.add_action(robot_state_publisher_node)
return ld
# EOF | 2,385 | Python | 36.873015 | 76 | 0.716981 |
NVIDIA-AI-IOT/isaac_demo/isaac_ros/src/carter_description/launch/display.launch.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch_ros.actions import Node
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.actions import IncludeLaunchDescription, DeclareLaunchArgument, Shutdown
from launch.conditions import IfCondition, UnlessCondition
from launch.substitutions import LaunchConfiguration
def generate_launch_description():
carter_description_path = get_package_share_directory('carter_description')
gui = LaunchConfiguration('gui')
rvizconfig = LaunchConfiguration('rvizconfig')
default_rviz_config_path = os.path.join(carter_description_path, 'rviz', 'urdf.rviz')
declare_gui_cmd = DeclareLaunchArgument(
name='gui',
default_value='False',
description='Flag to enable joint_state_publisher_gui')
declare_rvizconfig_cmd = DeclareLaunchArgument(
name='rvizconfig',
default_value=default_rviz_config_path,
description='Absolute path to rviz config file')
joint_state_publisher_gui_node = Node(
package='joint_state_publisher_gui',
executable='joint_state_publisher_gui',
name='joint_state_publisher_gui',
condition=IfCondition(gui),
on_exit=Shutdown()
)
joint_state_publisher_node = Node(
package='joint_state_publisher',
executable='joint_state_publisher',
name='joint_state_publisher',
condition=UnlessCondition(gui)
)
rviz_node = Node(
package='rviz2',
executable='rviz2',
name='rviz2',
output='screen',
arguments=['-d', rvizconfig],
on_exit=Shutdown()
)
# Nanosaur description launch
# https://answers.ros.org/question/306935/ros2-include-a-launch-file-from-a-launch-file/
description_launch = IncludeLaunchDescription(
PythonLaunchDescriptionSource([carter_description_path, '/launch/description.launch.py']),
)
# Define LaunchDescription variable and return it
ld = LaunchDescription()
ld.add_action(declare_gui_cmd)
ld.add_action(declare_rvizconfig_cmd)
ld.add_action(description_launch)
ld.add_action(joint_state_publisher_node)
ld.add_action(joint_state_publisher_gui_node)
ld.add_action(rviz_node)
return ld
# EOF | 3,489 | Python | 37.351648 | 98 | 0.725423 |
RoboEagles4828/2023RobotROS/README.md | # 2023RobotROS
ROS Code for the 2023 Robot
## Requirements
-------
- Ubuntu 20.04
- RTX Enabled GPU
# Workstation Setup steps
### 1. ROS2 Setup
- **Install ROS2 Galactic** \
`sudo ./scripts/install-ros2-galactic.sh`
- **Install ROS VS Code Extension** \
Go to extensions and search for ROS and click install
- **Install Workspace Dependencies** \
Press F1, and run this command: \
`ROS: Install ROS Dependencies for this workspace using rosdep`
- **Build the packages** \
Shortcut: `ctrl + shift + b` \
or \
Terminal: `colcon build --symlink-install`
- **Done with ROS2 Setup**
### 2. Isaac Sim Setup
- **Install Nvidia Drivers** \
`sudo apt-get install nvidia-driver-515`
- **Download Omniverse Launcher** \
https://www.nvidia.com/en-us/omniverse/download/
- **Run Omniverse** \
`chmod +x omniverse-launcher-linux.AppImage` \
`./omniverse-launcher-linux.AppImage`
- **Install Cache and Isaac Sim from the exchange** \
Wait until both are downloaded and installed.
- **Make ROS2 the default bridge** \
`sudo ./scripts/use-isaac-ros2-bridge.sh`
- **Launch Isaac Sim** \
Initial load can take a while
- **Open the extension manager** \
`Window -> Extensions`
- **Import the Swerve Bot Extension** \
Hit the gear icon near the search bar. \
Inside Extension Search Paths, Hit the + icon and put the path \
`<path-to-repo>/2023RobotROS/isaac`
- **Enable the Extension** \
Search for the Swerve Bot extension. \
Click on the extension. \
Click on the enable toggle switch and Autoload checkbox
- **DONE with Isaac Sim Setup**
# Running Swerve Bot
1. Connect an xbox controller
2. Hit load on the *Import URDF* extension window
3. Press Play on the left hand side
4. From this repo directory run \
`source install/setup.bash` \
`ros2 launch swerve_description isaac.launch.py`
5. Use the controller to move the robot around | 1,840 | Markdown | 23.878378 | 64 | 0.718478 |
RoboEagles4828/2023RobotROS/src/swerve_hardware/swerve_hardware.xml | <library path="swerve_hardware">
<class name="swerve_hardware/IsaacDriveHardware"
type="swerve_hardware::IsaacDriveHardware"
base_class_type="hardware_interface::SystemInterface">
<description>
The ROS2 Control hardware interface to talk with Isaac Sim robot drive train.
</description>
</class>
<class name="swerve_hardware/TestDriveHardware"
type="swerve_hardware::TestDriveHardware"
base_class_type="hardware_interface::SystemInterface">
<description>
The ROS2 Control hardware interface for testing a connected controller.
</description>
</class>
</library> | 634 | XML | 36.352939 | 83 | 0.714511 |
RoboEagles4828/2023RobotROS/src/swerve_hardware/src/test_drive.cpp | // Copyright 2021 ros2_control Development Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "swerve_hardware/test_drive.hpp"
#include <chrono>
#include <cmath>
#include <limits>
#include <memory>
#include <vector>
#include "hardware_interface/types/hardware_interface_type_values.hpp"
#include "rclcpp/rclcpp.hpp"
using std::placeholders::_1;
namespace swerve_hardware
{
CallbackReturn TestDriveHardware::on_init(const hardware_interface::HardwareInfo & info)
{
// INTERFACE SETUP
if (hardware_interface::SystemInterface::on_init(info) != CallbackReturn::SUCCESS)
{
return CallbackReturn::ERROR;
}
// 8 positions states, 4 axle positions 4 wheel positions
hw_positions_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN());
// 8 velocity states, 4 axle velocity 4 wheel velocity
hw_velocities_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN());
// 4 wheel velocity commands
hw_command_velocity_.resize(info_.joints.size()/2, std::numeric_limits<double>::quiet_NaN());
// 4 axle position commands
hw_command_position_.resize(info_.joints.size()/2, std::numeric_limits<double>::quiet_NaN());
for (const hardware_interface::ComponentInfo & joint : info_.joints)
{
joint_names_.push_back(joint.name);
if (joint.command_interfaces.size() != 1)
{
RCLCPP_FATAL(
rclcpp::get_logger("TestDriveHardware"),
"Joint '%s' has %zu command interfaces found. 1 expected.", joint.name.c_str(),
joint.command_interfaces.size());
return CallbackReturn::ERROR;
}
if (joint.command_interfaces[0].name != hardware_interface::HW_IF_VELOCITY && joint.command_interfaces[0].name != hardware_interface::HW_IF_POSITION)
{
RCLCPP_FATAL(
rclcpp::get_logger("TestDriveHardware"),
"Joint '%s' have %s command interfaces found. '%s' expected.", joint.name.c_str(),
joint.command_interfaces[0].name.c_str(), hardware_interface::HW_IF_VELOCITY);
return CallbackReturn::ERROR;
}
if (joint.state_interfaces.size() != 2)
{
RCLCPP_FATAL(
rclcpp::get_logger("TestDriveHardware"),
"Joint '%s' has %zu state interface. 2 expected.", joint.name.c_str(),
joint.state_interfaces.size());
return CallbackReturn::ERROR;
}
if (joint.state_interfaces[0].name != hardware_interface::HW_IF_POSITION)
{
RCLCPP_FATAL(
rclcpp::get_logger("TestDriveHardware"),
"Joint '%s' have '%s' as first state interface. '%s' expected.", joint.name.c_str(),
joint.state_interfaces[0].name.c_str(), hardware_interface::HW_IF_POSITION);
return CallbackReturn::ERROR;
}
if (joint.state_interfaces[1].name != hardware_interface::HW_IF_VELOCITY)
{
RCLCPP_FATAL(
rclcpp::get_logger("TestDriveHardware"),
"Joint '%s' have '%s' as second state interface. '%s' expected.", joint.name.c_str(),
joint.state_interfaces[1].name.c_str(), hardware_interface::HW_IF_VELOCITY);
return CallbackReturn::ERROR;
}
}
return CallbackReturn::SUCCESS;
}
std::vector<hardware_interface::StateInterface> TestDriveHardware::export_state_interfaces()
{
std::vector<hardware_interface::StateInterface> state_interfaces;
for (auto i = 0u; i < info_.joints.size(); i++)
{
state_interfaces.emplace_back(hardware_interface::StateInterface(
info_.joints[i].name, hardware_interface::HW_IF_POSITION, &hw_positions_[i]));
state_interfaces.emplace_back(hardware_interface::StateInterface(
info_.joints[i].name, hardware_interface::HW_IF_VELOCITY, &hw_velocities_[i]));
}
return state_interfaces;
}
std::vector<hardware_interface::CommandInterface> TestDriveHardware::export_command_interfaces()
{
std::vector<hardware_interface::CommandInterface> command_interfaces;
uint counter_position =0;
uint counter_velocity =0;
for (auto i = 0u; i < info_.joints.size(); i++)
{
auto joint = info_.joints[i];
RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Joint Name %s", joint.name.c_str());
if (joint.command_interfaces[0].name == hardware_interface::HW_IF_VELOCITY) {
RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Added Velocity Joint: %s", joint.name.c_str() );
command_interfaces.emplace_back(hardware_interface::CommandInterface(
joint.name, hardware_interface::HW_IF_VELOCITY, &hw_command_velocity_[counter_velocity]));
names_to_vel_cmd_map_[joint.name] = counter_velocity + 1; // ADD 1 to differentiate from a key that is not found
counter_velocity++;
} else {
RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Added Position Joint: %s", joint.name.c_str() );
command_interfaces.emplace_back(hardware_interface::CommandInterface(
joint.name, hardware_interface::HW_IF_POSITION, &hw_command_position_[counter_position]));
names_to_pos_cmd_map_[joint.name] = counter_position + 1; // ADD 1 to differentiate from a key that is not found
counter_position++;
}
}
return command_interfaces;
}
CallbackReturn TestDriveHardware::on_activate(
const rclcpp_lifecycle::State & /*previous_state*/)
{
RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Activating ...please wait...");
// Set Default Values for State Interface Arrays
for (auto i = 0u; i < hw_positions_.size(); i++)
{
hw_positions_[i] = 0.0;
hw_velocities_[i] = 0.0;
}
// Set Default Values for Command Interface Arrays
for (auto i = 0u; i < hw_command_velocity_.size(); i++)
{
hw_command_velocity_[i] = 0.0;
hw_command_position_[i] = 0.0;
}
RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Successfully activated!");
return CallbackReturn::SUCCESS;
}
CallbackReturn TestDriveHardware::on_deactivate(
const rclcpp_lifecycle::State & /*previous_state*/)
{
RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Deactivating ...please wait...");
RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Successfully deactivated!");
return CallbackReturn::SUCCESS;
}
// || ||
// \/ THE STUFF THAT MATTERS \/
hardware_interface::return_type TestDriveHardware::read()
{
// Dumb Pass Through
// If you give the command for x velocity then the state is x velocity
// Loop through each joint name
// Check if joint name is in velocity command map
// If it is, use the index from the map to get the value in the velocity array
// If velocity not in map, set velocity value to 0
// Perform the same for position
double dt = 0.01;
for (auto i = 0u; i < joint_names_.size(); i++)
{
auto vel_i = names_to_vel_cmd_map_[joint_names_[i]];
auto pos_i = names_to_pos_cmd_map_[joint_names_[i]];
if (vel_i > 0) {
// RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "J %f", hw_command_velocity_[vel_i - 1]);
auto vel = hw_command_velocity_[vel_i - 1];
hw_velocities_[i] = vel;
hw_positions_[i] = hw_positions_[i] + dt * vel;
} else if (pos_i > 0) {
auto pos = hw_command_position_[pos_i - 1];
hw_velocities_[i] = 0.0;
hw_positions_[i] = pos;
}
}
return hardware_interface::return_type::OK;
}
hardware_interface::return_type swerve_hardware::TestDriveHardware::write()
{
// Do Nothing
// Uncomment below if you want verbose messages for debugging.
for (auto i = 0u; i < hw_command_velocity_.size(); i++)
{
// RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Wheel %u Velocity: %f", i, hw_command_velocity_[i]);
}
return hardware_interface::return_type::OK;
}
} // namespace swerve_hardware
#include "pluginlib/class_list_macros.hpp"
PLUGINLIB_EXPORT_CLASS(
swerve_hardware::TestDriveHardware, hardware_interface::SystemInterface) | 8,298 | C++ | 33.012295 | 153 | 0.676549 |
RoboEagles4828/2023RobotROS/src/swerve_hardware/include/swerve_hardware/test_drive.hpp | // Copyright 2021 ros2_control Development Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef SWERVE_HARDWARE__TEST_DRIVE_HPP_
#define SWERVE_HARDWARE__TEST_DRIVE_HPP_
#include <memory>
#include <string>
#include <vector>
#include <map>
#include "hardware_interface/handle.hpp"
#include "hardware_interface/hardware_info.hpp"
#include "hardware_interface/system_interface.hpp"
#include "hardware_interface/types/hardware_interface_return_values.hpp"
#include "rclcpp/macros.hpp"
#include "rclcpp_lifecycle/node_interfaces/lifecycle_node_interface.hpp"
#include "rclcpp_lifecycle/state.hpp"
#include "swerve_hardware/visibility_control.h"
#include "rclcpp/rclcpp.hpp"
using CallbackReturn = rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn;
namespace swerve_hardware
{
class TestDriveHardware : public hardware_interface::SystemInterface
{
public:
RCLCPP_SHARED_PTR_DEFINITIONS(TestDriveHardware)
SWERVE_HARDWARE_PUBLIC
CallbackReturn on_init(const hardware_interface::HardwareInfo & info) override;
SWERVE_HARDWARE_PUBLIC
std::vector<hardware_interface::StateInterface> export_state_interfaces() override;
SWERVE_HARDWARE_PUBLIC
std::vector<hardware_interface::CommandInterface> export_command_interfaces() override;
SWERVE_HARDWARE_PUBLIC
CallbackReturn on_activate(const rclcpp_lifecycle::State & previous_state) override;
SWERVE_HARDWARE_PUBLIC
CallbackReturn on_deactivate(const rclcpp_lifecycle::State & previous_state) override;
SWERVE_HARDWARE_PUBLIC
hardware_interface::return_type read() override;
SWERVE_HARDWARE_PUBLIC
hardware_interface::return_type write() override;
private:
// Store the command for the simulated robot
std::vector<double> hw_command_velocity_;
std::vector<double> hw_command_position_;
// Map for easy lookup name -> joint command value
std::map<std::string, uint> names_to_vel_cmd_map_;
std::map<std::string, uint> names_to_pos_cmd_map_;
// The state vectors
std::vector<double> hw_positions_;
std::vector<double> hw_velocities_;
// Joint name array will align with state and command interface array
// The command at index 3 of hw_command_ will be the joint name at index 3 of joint_names
std::vector<std::string> joint_names_;
};
} // namespace swerve_hardware
#endif // SWERVE_HARDWARE__TEST_DRIVE_HPP_ | 2,857 | C++ | 33.433735 | 97 | 0.765838 |
RoboEagles4828/2023RobotROS/src/swerve_description/launch/test_hw.launch.py | import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.substitutions import LaunchConfiguration
from launch.actions import ExecuteProcess, IncludeLaunchDescription, RegisterEventHandler
from launch.event_handlers import OnProcessExit
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch_ros.actions import Node
import xacro
def generate_launch_description():
# SIM TIME MUST BE DISABLED
# sim time relys on a simulation to handle the ros clock.
# this launch uses fake hardware using the real clock.
use_sim_time = False
# Process the URDF file
pkg_path = os.path.join(get_package_share_directory('swerve_description'))
xacro_file = os.path.join(pkg_path,'urdf', 'robots','swerve.urdf.xacro')
controllers_file = os.path.join(pkg_path, 'config', 'controllers.yaml')
joystick_file = os.path.join(pkg_path, 'config', 'xbox-holonomic.config.yaml')
rviz_file = os.path.join(pkg_path, 'config', 'view.rviz')
# TODO: Make this as an arguement to the isaac launch file instead. These files are identical other than this.
swerve_description_config = xacro.process_file(xacro_file, mappings={ 'hw_interface_plugin': 'swerve_hardware/TestDriveHardware' })
# Save Built URDF file to Description Directory
swerve_description_xml = swerve_description_config.toxml()
source_code_path = os.path.abspath(os.path.join(pkg_path, "../../../../src/swerve_description"))
urdf_save_path = os.path.join(source_code_path, "swerve.urdf")
with open(urdf_save_path, 'w') as f:
f.write(swerve_description_xml)
# Create a robot_state_publisher node
params = {'robot_description': swerve_description_xml, 'use_sim_time': use_sim_time}
node_robot_state_publisher = Node(
package='robot_state_publisher',
executable='robot_state_publisher',
output='screen',
parameters=[params]
)
# Starts ROS2 Control
control_node = Node(
package="controller_manager",
executable="ros2_control_node",
parameters=[{'robot_description': swerve_description_xml, 'use_sim_time': use_sim_time }, controllers_file],
output="screen",
)
# Starts ROS2 Control Joint State Broadcaster
joint_state_broadcaster_spawner = Node(
package="controller_manager",
executable="spawner",
arguments=["joint_state_broadcaster", "--controller-manager", "/controller_manager"],
)
#Starts ROS2 Control Swerve Drive Controller
swerve_drive_controller_spawner = Node(
package="controller_manager",
executable="spawner",
arguments=["swerve_controller", "-c", "/controller_manager"],
)
swerve_drive_controller_delay = RegisterEventHandler(
event_handler=OnProcessExit(
target_action=joint_state_broadcaster_spawner,
on_exit=[swerve_drive_controller_spawner],
)
)
# Start Rviz2 with basic view
run_rviz2_node = Node(
package='rviz2',
executable='rviz2',
name='isaac_rviz2',
output='screen',
arguments=[["-d"], [rviz_file], '--ros-args', '--log-level', 'FATAL'],
)
rviz2_delay = RegisterEventHandler(
event_handler=OnProcessExit(
target_action=joint_state_broadcaster_spawner,
on_exit=[run_rviz2_node],
)
)
# Start Joystick Node
joy = Node(
package='joy',
executable='joy_node',
name='joy_node',
parameters=[{
'dev': '/dev/input/js0',
'deadzone': 0.3,
'autorepeat_rate': 20.0,
}])
# Start Teleop Node to translate joystick commands to robot commands
joy_teleop = Node(
package='teleop_twist_joy',
executable='teleop_node',
name='teleop_twist_joy_node',
parameters=[joystick_file],
remappings={('/cmd_vel', '/swerve_controller/cmd_vel_unstamped')}
)
# Launch!
return LaunchDescription([
control_node,
node_robot_state_publisher,
joint_state_broadcaster_spawner,
swerve_drive_controller_delay,
rviz2_delay,
joy,
joy_teleop
]) | 4,317 | Python | 33 | 135 | 0.646977 |
RoboEagles4828/2023RobotROS/src/swerve_description/config/controllers.yaml | controller_manager:
ros__parameters:
update_rate: 10 # Hz
joint_state_broadcaster:
type: joint_state_broadcaster/JointStateBroadcaster
swerve_controller:
type: swerve_controller/SwerveController
swerve_controller:
ros__parameters:
front_left_wheel_joint: "front_left_wheel_joint"
front_right_wheel_joint: "front_right_wheel_joint"
rear_left_wheel_joint: "back_left_wheel_joint"
rear_right_wheel_joint: "back_right_wheel_joint"
front_left_axle_joint: "front_left_axle_joint"
front_right_axle_joint: "front_right_axle_joint"
rear_left_axle_joint: "back_left_axle_joint"
rear_right_axle_joint: "back_right_axle_joint"
chassis_length: 0.7366
chassis_width: 0.7366
wheel_radius: 0.1016
cmd_vel_timeout: 10.0
use_stamped_vel: false | 810 | YAML | 30.192307 | 57 | 0.707407 |
RoboEagles4828/2023RobotROS/src/swerve_description/config/xbox-holonomic.config.yaml | teleop_twist_joy_node:
ros__parameters:
require_enable_button: false
axis_linear: # Left thumb stick vertical
x: 1
y: 0
scale_linear:
x: 5.0
y: 5.0
axis_angular: # Right thumb stick horizontal
yaw: 2
scale_angular:
yaw: 3.14159
enable_button: 2 # Left trigger button
enable_turbo_button: 5 # Right trigger button
| 391 | YAML | 20.777777 | 50 | 0.601023 |
RoboEagles4828/2023RobotROS/src/test_swerve_control/test_swerve_control/publish_twist_command.py | import rclpy
from rclpy.node import Node
from geometry_msgs.msg import Twist, Vector3
class PublishTwistCmd(Node):
def __init__(self):
super().__init__('publish_twist_commands')
self.publisher_ = self.create_publisher(Twist, 'swerve_controller/cmd_vel_unstamped', 10)
timer_period = 0.5 # seconds
self.timer = self.create_timer(timer_period, self.timer_callback)
self.i = 0
def timer_callback(self):
twist = Twist()
twist.linear.x = 2.0
twist.linear.y = 100.0
twist.angular.z = 4.0
self.publisher_.publish(twist)
self.get_logger().info('Publishing: ...')
self.i += 1
def main(args=None):
rclpy.init(args=args)
node = PublishTwistCmd()
rclpy.spin(node)
node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main() | 870 | Python | 22.54054 | 97 | 0.6 |
RoboEagles4828/2023RobotROS/src/swerve_controller/swerve_plugin.xml | <library path="swerve_controller">
<class name="swerve_controller/SwerveController" type="swerve_controller::SwerveController" base_class_type="controller_interface::ControllerInterface">
<description>
The swerve controller transforms linear and angular velocity messages into signals for each wheel(s) and swerve modules.
</description>
</class>
</library>
| 370 | XML | 45.374994 | 154 | 0.783784 |
RoboEagles4828/2023RobotROS/src/swerve_controller/src/swerve_controller.cpp | // Copyright 2020 PAL Robotics S.L.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*
* Author: Bence Magyar, Enrique Fernández, Manuel Meraz
*/
#include <memory>
#include <queue>
#include <string>
#include <utility>
#include <vector>
#include <cmath>
#include "swerve_controller/swerve_controller.hpp"
#include "hardware_interface/types/hardware_interface_type_values.hpp"
#include "lifecycle_msgs/msg/state.hpp"
#include "rclcpp/logging.hpp"
namespace
{
constexpr auto DEFAULT_COMMAND_TOPIC = "~/cmd_vel";
constexpr auto DEFAULT_COMMAND_UNSTAMPED_TOPIC = "~/cmd_vel_unstamped";
constexpr auto DEFAULT_COMMAND_OUT_TOPIC = "~/cmd_vel_out";
} // namespace
namespace swerve_controller
{
using namespace std::chrono_literals;
using controller_interface::interface_configuration_type;
using controller_interface::InterfaceConfiguration;
using hardware_interface::HW_IF_POSITION;
using hardware_interface::HW_IF_VELOCITY;
using lifecycle_msgs::msg::State;
Wheel::Wheel(std::reference_wrapper<hardware_interface::LoanedCommandInterface> velocity,
std::string name) : velocity_(velocity), name(std::move(name)) {}
void Wheel::set_velocity(double velocity)
{
velocity_.get().set_value(velocity);
}
Axle::Axle(std::reference_wrapper<hardware_interface::LoanedCommandInterface> position,
std::string name) : position_(position), name(std::move(name)) {}
void Axle::set_position(double position)
{
position_.get().set_value(position);
}
SwerveController::SwerveController() : controller_interface::ControllerInterface() {}
CallbackReturn SwerveController::on_init()
{
try
{
// with the lifecycle node being initialized, we can declare parameters
auto_declare<std::string>("front_left_wheel_joint", front_left_wheel_joint_name_);
auto_declare<std::string>("front_right_wheel_joint", front_right_wheel_joint_name_);
auto_declare<std::string>("rear_left_wheel_joint", rear_left_wheel_joint_name_);
auto_declare<std::string>("rear_right_wheel_joint", rear_right_wheel_joint_name_);
auto_declare<std::string>("front_left_axle_joint", front_left_axle_joint_name_);
auto_declare<std::string>("front_right_axle_joint", front_right_axle_joint_name_);
auto_declare<std::string>("rear_left_axle_joint", rear_left_axle_joint_name_);
auto_declare<std::string>("rear_right_axle_joint", rear_right_axle_joint_name_);
auto_declare<double>("chassis_length", wheel_params_.x_offset);
auto_declare<double>("chassis_width", wheel_params_.y_offset);
auto_declare<double>("wheel_radius", wheel_params_.radius);
auto_declare<double>("cmd_vel_timeout", cmd_vel_timeout_.count() / 1000.0);
auto_declare<bool>("use_stamped_vel", use_stamped_vel_);
}
catch (const std::exception & e)
{
fprintf(stderr, "Exception thrown during init stage with message: %s \n", e.what());
return CallbackReturn::ERROR;
}
return CallbackReturn::SUCCESS;
}
InterfaceConfiguration SwerveController::command_interface_configuration() const
{
std::vector<std::string> conf_names;
conf_names.push_back(front_left_wheel_joint_name_ + "/" + HW_IF_VELOCITY);
conf_names.push_back(front_right_wheel_joint_name_ + "/" + HW_IF_VELOCITY);
conf_names.push_back(rear_left_wheel_joint_name_ + "/" + HW_IF_VELOCITY);
conf_names.push_back(rear_right_wheel_joint_name_ + "/" + HW_IF_VELOCITY);
conf_names.push_back(front_left_axle_joint_name_ + "/" + HW_IF_POSITION);
conf_names.push_back(front_right_axle_joint_name_ + "/" + HW_IF_POSITION);
conf_names.push_back(rear_left_axle_joint_name_ + "/" + HW_IF_POSITION);
conf_names.push_back(rear_right_axle_joint_name_ + "/" + HW_IF_POSITION);
return {interface_configuration_type::INDIVIDUAL, conf_names};
}
InterfaceConfiguration SwerveController::state_interface_configuration() const
{
return {interface_configuration_type::NONE};
}
controller_interface::return_type SwerveController::update(
const rclcpp::Time & time, const rclcpp::Duration & /*period*/)
{
auto logger = node_->get_logger();
if (get_state().id() == State::PRIMARY_STATE_INACTIVE)
{
if (!is_halted)
{
halt();
is_halted = true;
}
return controller_interface::return_type::OK;
}
const auto current_time = time;
std::shared_ptr<Twist> last_command_msg;
received_velocity_msg_ptr_.get(last_command_msg);
if (last_command_msg == nullptr)
{
RCLCPP_WARN(logger, "Velocity message received was a nullptr.");
return controller_interface::return_type::ERROR;
}
const auto age_of_last_command = current_time - last_command_msg->header.stamp;
// Brake if cmd_vel has timeout, override the stored command
if (age_of_last_command > cmd_vel_timeout_)
{
last_command_msg->twist.linear.x = 0.0;
last_command_msg->twist.angular.z = 0.0;
}
Twist command = *last_command_msg;
double & linear_x_cmd = command.twist.linear.x;
double & linear_y_cmd = command.twist.linear.y;
double & angular_cmd = command.twist.angular.z;
double x_offset = wheel_params_.x_offset;
double radius = wheel_params_.radius;
// Compute Wheel Velocities and Positions
const double a = linear_x_cmd - angular_cmd * x_offset / 2;
const double b = linear_x_cmd + angular_cmd * x_offset / 2;
const double c = linear_y_cmd - angular_cmd * x_offset / 2;
const double d = linear_y_cmd + angular_cmd * x_offset / 2;
const double front_left_velocity = (sqrt( pow( b , 2) + pow ( d , 2) ) )*(1/(radius*M_PI));
const double front_right_velocity = (sqrt( pow( b , 2) + pow( c , 2 ) ) )*(1/(radius*M_PI));
const double rear_left_velocity = (sqrt( pow( a , 2 ) + pow( d , 2) ) )*(1/(radius*M_PI));
const double rear_right_velocity = (sqrt( pow( a, 2 ) + pow( c , 2) ) )*(1/(radius*M_PI));
const double front_left_position = atan2(b,d);
const double front_right_position = atan2(b,c);
const double rear_left_position = atan2(a,d);
const double rear_right_postition = atan2(a,c);
// Set Wheel Velocities
front_left_handle_->set_velocity(front_left_velocity);
front_right_handle_->set_velocity(front_right_velocity);
rear_left_handle_->set_velocity(rear_left_velocity);
rear_right_handle_->set_velocity(rear_right_velocity);
// Set Wheel Positions
front_left_handle_2_->set_position(front_left_position);
front_right_handle_2_->set_position(front_right_position);
rear_left_handle_2_->set_position(rear_left_position);
rear_right_handle_2_->set_position(rear_right_postition);
// Time update
const auto update_dt = current_time - previous_update_timestamp_;
previous_update_timestamp_ = current_time;
return controller_interface::return_type::OK;
}
CallbackReturn SwerveController::on_configure(const rclcpp_lifecycle::State &)
{
auto logger = node_->get_logger();
// Get Parameters
front_left_wheel_joint_name_ = node_->get_parameter("front_left_wheel_joint").as_string();
front_right_wheel_joint_name_ = node_->get_parameter("front_right_wheel_joint").as_string();
rear_left_wheel_joint_name_ = node_->get_parameter("rear_left_wheel_joint").as_string();
rear_right_wheel_joint_name_ = node_->get_parameter("rear_right_wheel_joint").as_string();
front_left_axle_joint_name_ = node_->get_parameter("front_left_axle_joint").as_string();
front_right_axle_joint_name_ = node_->get_parameter("front_right_axle_joint").as_string();
rear_left_axle_joint_name_ = node_->get_parameter("rear_left_axle_joint").as_string();
rear_right_axle_joint_name_ = node_->get_parameter("rear_right_axle_joint").as_string();
if (front_left_wheel_joint_name_.empty()) {
RCLCPP_ERROR(logger, "front_left_wheel_joint_name is not set");
return CallbackReturn::ERROR;
}
if (front_right_wheel_joint_name_.empty()) {
RCLCPP_ERROR(logger, "front_right_wheel_joint_name is not set");
return CallbackReturn::ERROR;
}
if (rear_left_wheel_joint_name_.empty()) {
RCLCPP_ERROR(logger, "rear_left_wheel_joint_name is not set");
return CallbackReturn::ERROR;
}
if (rear_right_wheel_joint_name_.empty()) {
RCLCPP_ERROR(logger, "rear_right_wheel_joint_name is not set");
return CallbackReturn::ERROR;
}
if (front_left_axle_joint_name_.empty()) {
RCLCPP_ERROR(logger, "front_left_axle_joint_name is not set");
return CallbackReturn::ERROR;
}
if (front_right_axle_joint_name_.empty()) {
RCLCPP_ERROR(logger, "front_right_axle_joint_name is not set");
return CallbackReturn::ERROR;
}
if (rear_left_axle_joint_name_.empty()) {
RCLCPP_ERROR(logger, "rear_left_axle_joint_name is not set");
return CallbackReturn::ERROR;
}
if (rear_right_axle_joint_name_.empty()) {
RCLCPP_ERROR(logger, "rear_right_axle_joint_name is not set");
return CallbackReturn::ERROR;
}
wheel_params_.x_offset = node_->get_parameter("chassis_length").as_double();
wheel_params_.y_offset = node_->get_parameter("chassis_width").as_double();
wheel_params_.radius = node_->get_parameter("wheel_radius").as_double();
cmd_vel_timeout_ = std::chrono::milliseconds{
static_cast<int>(node_->get_parameter("cmd_vel_timeout").as_double() * 1000.0)};
use_stamped_vel_ = node_->get_parameter("use_stamped_vel").as_bool();
// Run reset to make sure everything is initialized correctly
if (!reset())
{
return CallbackReturn::ERROR;
}
const Twist empty_twist;
received_velocity_msg_ptr_.set(std::make_shared<Twist>(empty_twist));
// initialize command subscriber
if (use_stamped_vel_)
{
velocity_command_subscriber_ = node_->create_subscription<Twist>(
DEFAULT_COMMAND_TOPIC, rclcpp::SystemDefaultsQoS(),
[this](const std::shared_ptr<Twist> msg) -> void {
if (!subscriber_is_active_)
{
RCLCPP_WARN(node_->get_logger(), "Can't accept new commands. subscriber is inactive");
return;
}
if ((msg->header.stamp.sec == 0) && (msg->header.stamp.nanosec == 0))
{
RCLCPP_WARN_ONCE(
node_->get_logger(),
"Received TwistStamped with zero timestamp, setting it to current "
"time, this message will only be shown once");
msg->header.stamp = node_->get_clock()->now();
}
received_velocity_msg_ptr_.set(std::move(msg));
});
}
else
{
velocity_command_unstamped_subscriber_ = node_->create_subscription<geometry_msgs::msg::Twist>(
DEFAULT_COMMAND_UNSTAMPED_TOPIC, rclcpp::SystemDefaultsQoS(),
[this](const std::shared_ptr<geometry_msgs::msg::Twist> msg) -> void {
if (!subscriber_is_active_)
{
RCLCPP_WARN(node_->get_logger(), "Can't accept new commands. subscriber is inactive");
return;
}
// Write fake header in the stored stamped command
std::shared_ptr<Twist> twist_stamped;
received_velocity_msg_ptr_.get(twist_stamped);
twist_stamped->twist = *msg;
twist_stamped->header.stamp = node_->get_clock()->now();
});
}
previous_update_timestamp_ = node_->get_clock()->now();
return CallbackReturn::SUCCESS;
}
CallbackReturn SwerveController::on_activate(const rclcpp_lifecycle::State &)
{
front_left_handle_ = get_wheel(front_left_wheel_joint_name_);
front_right_handle_ = get_wheel(front_right_wheel_joint_name_);
rear_left_handle_ = get_wheel(rear_left_wheel_joint_name_);
rear_right_handle_ = get_wheel(rear_right_wheel_joint_name_);
front_left_handle_2_ = get_axle(front_left_axle_joint_name_);
front_right_handle_2_ = get_axle(front_right_axle_joint_name_);
rear_left_handle_2_ = get_axle(rear_left_axle_joint_name_);
rear_right_handle_2_ = get_axle(rear_right_axle_joint_name_);
if (!front_left_handle_ || !front_right_handle_ || !rear_left_handle_ || !rear_right_handle_||!front_left_handle_2_ || !front_right_handle_2_ || !rear_left_handle_2_ || !rear_right_handle_2_)
{
return CallbackReturn::ERROR;
}
is_halted = false;
subscriber_is_active_ = true;
RCLCPP_DEBUG(node_->get_logger(), "Subscriber and publisher are now active.");
return CallbackReturn::SUCCESS;
}
CallbackReturn SwerveController::on_deactivate(const rclcpp_lifecycle::State &)
{
subscriber_is_active_ = false;
return CallbackReturn::SUCCESS;
}
CallbackReturn SwerveController::on_cleanup(const rclcpp_lifecycle::State &)
{
if (!reset())
{
return CallbackReturn::ERROR;
}
received_velocity_msg_ptr_.set(std::make_shared<Twist>());
return CallbackReturn::SUCCESS;
}
CallbackReturn SwerveController::on_error(const rclcpp_lifecycle::State &)
{
if (!reset())
{
return CallbackReturn::ERROR;
}
return CallbackReturn::SUCCESS;
}
bool SwerveController::reset()
{
subscriber_is_active_ = false;
velocity_command_subscriber_.reset();
velocity_command_unstamped_subscriber_.reset();
received_velocity_msg_ptr_.set(nullptr);
is_halted = false;
return true;
}
CallbackReturn SwerveController::on_shutdown(const rclcpp_lifecycle::State &)
{
return CallbackReturn::SUCCESS;
}
void SwerveController::halt()
{
front_left_handle_->set_velocity(0.0);
front_right_handle_->set_velocity(0.0);
rear_left_handle_->set_velocity(0.0);
rear_right_handle_->set_velocity(0.0);
auto logger = node_->get_logger();
RCLCPP_WARN(logger, "-----HALT CALLED : STOPPING ALL MOTORS-----");
}
std::shared_ptr<Wheel> SwerveController::get_wheel( const std::string & wheel_name )
{
auto logger = node_->get_logger();
if (wheel_name.empty())
{
RCLCPP_ERROR(logger, "Wheel joint name not given. Make sure all joints are specified.");
return nullptr;
}
// Get Command Handle for joint
const auto command_handle = std::find_if(
command_interfaces_.begin(), command_interfaces_.end(),
[&wheel_name](const auto & interface) {
return interface.get_name() == wheel_name &&
interface.get_interface_name() == HW_IF_VELOCITY;
});
if (command_handle == command_interfaces_.end())
{
RCLCPP_ERROR(logger, "Unable to obtain joint command handle for %s", wheel_name.c_str());
return nullptr;
}
return std::make_shared<Wheel>(std::ref(*command_handle), wheel_name);
}
std::shared_ptr<Axle> SwerveController::get_axle( const std::string & axle_name )
{
auto logger = node_->get_logger();
if (axle_name.empty())
{
RCLCPP_ERROR(logger, "Wheel joint name not given. Make sure all joints are specified.");
return nullptr;
}
// Get Command Handle for joint
const auto command_handle = std::find_if(
command_interfaces_.begin(), command_interfaces_.end(),
[&axle_name](const auto & interface) {
return interface.get_name() == axle_name &&
interface.get_interface_name() == HW_IF_POSITION;
});
if (command_handle == command_interfaces_.end())
{
RCLCPP_ERROR(logger, "Unable to obtain joint command handle for %s", axle_name.c_str());
return nullptr;
}
return std::make_shared<Axle>(std::ref(*command_handle), axle_name);
}
} // namespace swerve_controller
#include "class_loader/register_macro.hpp"
CLASS_LOADER_REGISTER_CLASS(
swerve_controller::SwerveController, controller_interface::ControllerInterface)
| 15,639 | C++ | 34.87156 | 193 | 0.684954 |
RoboEagles4828/2023RobotROS/src/swerve_controller/include/swerve_controller/swerve_controller.hpp | // Copyright 2020 PAL Robotics S.L.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*
* Author: Bence Magyar, Enrique Fernández, Manuel Meraz
*/
#ifndef SWERVE_CONTROLLER__SWERVE_CONTROLLER_HPP_
#define SWERVE_CONTROLLER__SWERVE_CONTROLLER_HPP_
#include <chrono>
#include <cmath>
#include <memory>
#include <queue>
#include <string>
#include <vector>
#include "controller_interface/controller_interface.hpp"
#include "swerve_controller/visibility_control.h"
#include "geometry_msgs/msg/twist.hpp"
#include "geometry_msgs/msg/twist_stamped.hpp"
#include "hardware_interface/handle.hpp"
#include "rclcpp/rclcpp.hpp"
#include "rclcpp_lifecycle/state.hpp"
#include "realtime_tools/realtime_box.h"
#include "realtime_tools/realtime_buffer.h"
#include "realtime_tools/realtime_publisher.h"
#include <hardware_interface/loaned_command_interface.hpp>
namespace swerve_controller
{
using CallbackReturn = rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn;
class Wheel {
public:
Wheel(std::reference_wrapper<hardware_interface::LoanedCommandInterface> velocity, std::string name);
void set_velocity(double velocity);
private:
std::reference_wrapper<hardware_interface::LoanedCommandInterface> velocity_;
std::string name;
};
class Axle {
public:
Axle(std::reference_wrapper<hardware_interface::LoanedCommandInterface> position, std::string name);
void set_position(double position);
private:
std::reference_wrapper<hardware_interface::LoanedCommandInterface> position_;
std::string name;
};
class SwerveController : public controller_interface::ControllerInterface
{
using Twist = geometry_msgs::msg::TwistStamped;
public:
SWERVE_CONTROLLER_PUBLIC
SwerveController();
SWERVE_CONTROLLER_PUBLIC
controller_interface::InterfaceConfiguration command_interface_configuration() const override;
SWERVE_CONTROLLER_PUBLIC
controller_interface::InterfaceConfiguration state_interface_configuration() const override;
SWERVE_CONTROLLER_PUBLIC
controller_interface::return_type update(
const rclcpp::Time & time, const rclcpp::Duration & period) override;
SWERVE_CONTROLLER_PUBLIC
CallbackReturn on_init() override;
SWERVE_CONTROLLER_PUBLIC
CallbackReturn on_configure(const rclcpp_lifecycle::State & previous_state) override;
SWERVE_CONTROLLER_PUBLIC
CallbackReturn on_activate(const rclcpp_lifecycle::State & previous_state) override;
SWERVE_CONTROLLER_PUBLIC
CallbackReturn on_deactivate(const rclcpp_lifecycle::State & previous_state) override;
SWERVE_CONTROLLER_PUBLIC
CallbackReturn on_cleanup(const rclcpp_lifecycle::State & previous_state) override;
SWERVE_CONTROLLER_PUBLIC
CallbackReturn on_error(const rclcpp_lifecycle::State & previous_state) override;
SWERVE_CONTROLLER_PUBLIC
CallbackReturn on_shutdown(const rclcpp_lifecycle::State & previous_state) override;
protected:
std::shared_ptr<Wheel> get_wheel(const std::string & wheel_name);
std::shared_ptr<Axle> get_axle(const std::string & axle_name);
std::shared_ptr<Wheel> front_left_handle_;
std::shared_ptr<Wheel> front_right_handle_;
std::shared_ptr<Wheel> rear_left_handle_;
std::shared_ptr<Wheel> rear_right_handle_;
std::shared_ptr<Axle> front_left_handle_2_;
std::shared_ptr<Axle> front_right_handle_2_;
std::shared_ptr<Axle> rear_left_handle_2_;
std::shared_ptr<Axle> rear_right_handle_2_;
std::string front_left_wheel_joint_name_;
std::string front_right_wheel_joint_name_;
std::string rear_left_wheel_joint_name_;
std::string rear_right_wheel_joint_name_;
std::string front_left_axle_joint_name_;
std::string front_right_axle_joint_name_;
std::string rear_left_axle_joint_name_;
std::string rear_right_axle_joint_name_;
struct WheelParams
{
double x_offset = 0.0; // Chassis Center to Axle Center
double y_offset = 0.0; // Axle Center to Wheel Center
double radius = 0.0; // Assumed to be the same for all wheels
} wheel_params_;
// Timeout to consider cmd_vel commands old
std::chrono::milliseconds cmd_vel_timeout_{500};
rclcpp::Time previous_update_timestamp_{0};
// Topic Subscription
bool subscriber_is_active_ = false;
rclcpp::Subscription<Twist>::SharedPtr velocity_command_subscriber_ = nullptr;
rclcpp::Subscription<geometry_msgs::msg::Twist>::SharedPtr
velocity_command_unstamped_subscriber_ = nullptr;
realtime_tools::RealtimeBox<std::shared_ptr<Twist>> received_velocity_msg_ptr_{nullptr};
bool is_halted = false;
bool use_stamped_vel_ = true;
bool reset();
void halt();
};
} // namespace swerve_controllerS
#endif // Swerve_CONTROLLER__SWERVE_CONTROLLER_HPP_
| 5,166 | C++ | 32.993421 | 105 | 0.753388 |
RoboEagles4828/2023RobotROS/src/swerve_controller/include/swerve_controller/visibility_control.h | // Copyright 2017 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/* This header must be included by all rclcpp headers which declare symbols
* which are defined in the rclcpp library. When not building the rclcpp
* library, i.e. when using the headers in other package's code, the contents
* of this header change the visibility of certain symbols which the rclcpp
* library cannot have, but the consuming code must have inorder to link.
*/
#ifndef SWERVE_CONTROLLER__VISIBILITY_CONTROL_H_
#define SWERVE_CONTROLLER__VISIBILITY_CONTROL_H_
// This logic was borrowed (then namespaced) from the examples on the gcc wiki:
// https://gcc.gnu.org/wiki/Visibility
#if defined _WIN32 || defined __CYGWIN__
#ifdef __GNUC__
#define SWERVE_CONTROLLER_EXPORT __attribute__((dllexport))
#define SWERVE_CONTROLLER_IMPORT __attribute__((dllimport))
#else
#define SWERVE_CONTROLLER_EXPORT __declspec(dllexport)
#define SWERVE_CONTROLLER_IMPORT __declspec(dllimport)
#endif
#ifdef SWERVE_CONTROLLER_BUILDING_DLL
#define SWERVE_CONTROLLER_PUBLIC SWERVE_CONTROLLER_EXPORT
#else
#define SWERVE_CONTROLLER_PUBLIC SWERVE_CONTROLLER_IMPORT
#endif
#define SWERVE_CONTROLLER_PUBLIC_TYPE SWERVE_CONTROLLER_PUBLIC
#define SWERVE_CONTROLLER_LOCAL
#else
#define SWERVE_CONTROLLER_EXPORT __attribute__((visibility("default")))
#define SWERVE_CONTROLLER_IMPORT
#if __GNUC__ >= 4
#define SWERVE_CONTROLLER_PUBLIC __attribute__((visibility("default")))
#define SWERVE_CONTROLLER_LOCAL __attribute__((visibility("hidden")))
#else
#define SWERVE_CONTROLLER_PUBLIC
#define SWERVE_CONTROLLER_LOCAL
#endif
#define SWERVE_CONTROLLER_PUBLIC_TYPE
#endif
#endif // SWERVE_CONTROLLER__VISIBILITY_CONTROL_H_
| 2,229 | C | 38.122806 | 79 | 0.767609 |
RoboEagles4828/2023RobotROS/isaac/omni.isaac.swerve_bot/omni/isaac/swerve_bot/import_bot/__init__.py |
from omni.isaac.swerve_bot.import_bot.import_bot import ImportBot
from omni.isaac.swerve_bot.import_bot.import_bot_extension import ImportBotExtension
| 152 | Python | 37.249991 | 84 | 0.842105 |
RoboEagles4828/2023RobotROS/isaac/omni.isaac.swerve_bot/omni/isaac/swerve_bot/import_bot/import_bot.py | import omni.graph.core as og
import omni.usd
from omni.isaac.swerve_bot.base_sample import BaseSample
from omni.isaac.urdf import _urdf
from omni.isaac.core.robots import Robot
from omni.isaac.core.utils import prims
from omni.isaac.core_nodes.scripts.utils import set_target_prims
from omni.kit.viewport_legacy import get_default_viewport_window
from pxr import UsdPhysics
import omni.kit.commands
import os
import numpy as np
import math
import carb
def set_drive_params(drive, stiffness, damping, max_force):
drive.GetStiffnessAttr().Set(stiffness)
drive.GetDampingAttr().Set(damping)
if(max_force != 0.0):
drive.GetMaxForceAttr().Set(max_force)
return
class ImportBot(BaseSample):
def __init__(self) -> None:
super().__init__()
return
def setup_scene(self):
world = self.get_world()
world.scene.add_default_ground_plane()
self.setup_perspective_cam()
self.setup_world_action_graph()
return
async def setup_post_load(self):
self._world = self.get_world()
self.robot_name = "Swerve"
self.extension_path = os.path.abspath(__file__)
self.project_root_path = os.path.abspath(os.path.join(self.extension_path, "../../../../../../.."))
self.path_to_urdf = os.path.join(self.project_root_path, "src/swerve_description/swerve.urdf")
carb.log_info(self.path_to_urdf)
self._robot_prim_path = self.import_robot(self.path_to_urdf)
if self._robot_prim_path is None:
print("Error: failed to import robot")
return
self._robot_prim = self._world.scene.add(
Robot(prim_path=self._robot_prim_path, name=self.robot_name, position=np.array([0.0, 0.0, 0.3]))
)
self.configure_robot(self._robot_prim_path)
return
def import_robot(self, urdf_path):
import_config = _urdf.ImportConfig()
import_config.merge_fixed_joints = False
import_config.fix_base = False
import_config.make_default_prim = True
import_config.self_collision = False
import_config.create_physics_scene = False
import_config.import_inertia_tensor = True
import_config.default_drive_strength = 1047.19751
import_config.default_position_drive_damping = 52.35988
import_config.default_drive_type = _urdf.UrdfJointTargetType.JOINT_DRIVE_VELOCITY
import_config.distance_scale = 1.0
import_config.density = 0.0
result, prim_path = omni.kit.commands.execute( "URDFParseAndImportFile",
urdf_path=urdf_path,
import_config=import_config)
if result:
return prim_path
return None
def configure_robot(self, robot_prim_path):
w_sides = ['left', 'right']
l_sides = ['front', 'back']
stage = self._world.stage
chassis_name = "swerve_chassis_link"
front_left_axle = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/{chassis_name}/front_left_axle_joint"), "angular")
front_right_axle = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/{chassis_name}/front_right_axle_joint"), "angular")
back_left_axle = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/{chassis_name}/back_left_axle_joint"), "angular")
back_right_axle = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/{chassis_name}/back_right_axle_joint"), "angular")
front_left_wheel = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/front_left_axle_link/front_left_wheel_joint"), "angular")
front_right_wheel = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/front_right_axle_link/front_right_wheel_joint"), "angular")
back_left_wheel = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/back_left_axle_link/back_left_wheel_joint"), "angular")
back_right_wheel = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/back_right_axle_link/back_right_wheel_joint"), "angular")
set_drive_params(front_left_axle, 10000000.0, 100000.0, 98.0)
set_drive_params(front_right_axle, 10000000.0, 100000.0, 98.0)
set_drive_params(back_left_axle, 10000000.0, 100000.0, 98.0)
set_drive_params(back_right_axle, 10000000.0, 100000.0, 98.0)
set_drive_params(front_left_wheel, 0, math.radians(1e5), 98.0)
set_drive_params(front_right_wheel, 0, math.radians(1e5), 98.0)
set_drive_params(back_left_wheel, 0, math.radians(1e5), 98.0)
set_drive_params(back_right_wheel, 0, math.radians(1e5), 98.0)
#self.create_lidar(robot_prim_path)
#self.create_depth_camera()
self.setup_robot_action_graph(robot_prim_path)
return
def create_lidar(self, robot_prim_path):
lidar_parent = "{}/lidar_link".format(robot_prim_path)
lidar_path = "/lidar"
self.lidar_prim_path = lidar_parent + lidar_path
result, prim = omni.kit.commands.execute(
"RangeSensorCreateLidar",
path=lidar_path,
parent=lidar_parent,
min_range=0.4,
max_range=25.0,
draw_points=False,
draw_lines=True,
horizontal_fov=360.0,
vertical_fov=30.0,
horizontal_resolution=0.4,
vertical_resolution=4.0,
rotation_rate=0.0,
high_lod=False,
yaw_offset=0.0,
enable_semantics=False
)
return
def create_depth_camera(self):
self.depth_left_camera_path = f"{self._robot_prim_path}/zed_left_camera_frame/left_cam"
self.depth_right_camera_path = f"{self._robot_prim_path}/zed_right_camera_frame/right_cam"
self.left_camera = prims.create_prim(
prim_path=self.depth_left_camera_path,
prim_type="Camera",
attributes={
"focusDistance": 1,
"focalLength": 24,
"horizontalAperture": 20.955,
"verticalAperture": 15.2908,
"clippingRange": (0.1, 1000000),
"clippingPlanes": np.array([1.0, 0.0, 1.0, 1.0]),
},
)
self.right_camera = prims.create_prim(
prim_path=self.depth_right_camera_path,
prim_type="Camera",
attributes={
"focusDistance": 1,
"focalLength": 24,
"horizontalAperture": 20.955,
"verticalAperture": 15.2908,
"clippingRange": (0.1, 1000000),
"clippingPlanes": np.array([1.0, 0.0, 1.0, 1.0]),
},
)
return
def setup_world_action_graph(self):
og.Controller.edit(
{"graph_path": "/globalclock", "evaluator_name": "execution"},
{
og.Controller.Keys.CREATE_NODES: [
("OnPlaybackTick", "omni.graph.action.OnPlaybackTick"),
("ReadSimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"),
("Context", "omni.isaac.ros2_bridge.ROS2Context"),
("PublishClock", "omni.isaac.ros2_bridge.ROS2PublishClock"),
],
og.Controller.Keys.CONNECT: [
("OnPlaybackTick.outputs:tick", "PublishClock.inputs:execIn"),
("Context.outputs:context", "PublishClock.inputs:context"),
("ReadSimTime.outputs:simulationTime", "PublishClock.inputs:timeStamp"),
],
}
)
return
def setup_perspective_cam(self):
# Get the Viewport and the Default Camera
viewport_window = get_default_viewport_window()
camera = self.get_world().stage.GetPrimAtPath(viewport_window.get_active_camera())
# Get Default Cam Values
camAttributes = {}
camOrientation = None
camTranslation = None
for att in camera.GetAttributes():
name = att.GetName()
if not (name.startswith('omni') or name.startswith('xform')):
camAttributes[att.GetName()] = att.Get()
elif name == 'xformOp:orient':
convertedQuat = [att.Get().GetReal()] + list(att.Get().GetImaginary())
camOrientation = np.array(convertedQuat)
elif name == 'xformOp:translate':
camTranslation = np.array(list(att.Get()))
# Modify what we want
camAttributes["clippingRange"] = (0.1, 1000000)
camAttributes["clippingPlanes"] = np.array([1.0, 0.0, 1.0, 1.0])
# Create a new camera with desired values
cam_path = "/World/PerspectiveCam"
prims.create_prim(
prim_path=cam_path,
prim_type="Camera",
translation=camTranslation,
orientation=camOrientation,
attributes=camAttributes,
)
# Use the camera for our viewport
viewport_window.set_active_camera(cam_path)
return
def setup_robot_action_graph(self, robot_prim_path):
robot_controller_path = f"{robot_prim_path}/ros_interface_controller"
og.Controller.edit(
{"graph_path": robot_controller_path, "evaluator_name": "execution"},
{
og.Controller.Keys.CREATE_NODES: [
("OnPlaybackTick", "omni.graph.action.OnPlaybackTick"),
("ReadSimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"),
("Context", "omni.isaac.ros2_bridge.ROS2Context"),
("PublishJointState", "omni.isaac.ros2_bridge.ROS2PublishJointState"),
("SubscribeJointState", "omni.isaac.ros2_bridge.ROS2SubscribeJointState"),
("articulation_controller", "omni.isaac.core_nodes.IsaacArticulationController"),
],
og.Controller.Keys.SET_VALUES: [
("PublishJointState.inputs:topicName", "isaac_joint_states"),
("SubscribeJointState.inputs:topicName", "isaac_joint_commands"),
("articulation_controller.inputs:usePath", False),
],
og.Controller.Keys.CONNECT: [
("OnPlaybackTick.outputs:tick", "PublishJointState.inputs:execIn"),
("OnPlaybackTick.outputs:tick", "SubscribeJointState.inputs:execIn"),
("OnPlaybackTick.outputs:tick", "articulation_controller.inputs:execIn"),
("ReadSimTime.outputs:simulationTime", "PublishJointState.inputs:timeStamp"),
("Context.outputs:context", "PublishJointState.inputs:context"),
("Context.outputs:context", "SubscribeJointState.inputs:context"),
("SubscribeJointState.outputs:jointNames", "articulation_controller.inputs:jointNames"),
("SubscribeJointState.outputs:velocityCommand", "articulation_controller.inputs:velocityCommand"),
("SubscribeJointState.outputs:positionCommand", "articulation_controller.inputs:positionCommand"),
],
}
)
set_target_prims(primPath=f"{robot_controller_path}/articulation_controller", targetPrimPaths=[robot_prim_path])
set_target_prims(primPath=f"{robot_controller_path}/PublishJointState", targetPrimPaths=[robot_prim_path])
return
async def setup_pre_reset(self):
return
async def setup_post_reset(self):
return
async def setup_post_clear(self):
return
def world_cleanup(self):
self._world.scene.remove_object(self.robot_name)
return
| 11,794 | Python | 43.509434 | 151 | 0.602255 |
RoboEagles4828/2023RobotROS/isaac/omni.isaac.swerve_bot/docs/CHANGELOG.md | **********
CHANGELOG
**********
[0.1.0] - 2022-6-26
[0.1.1] - 2022-10-15
========================
Added
-------
- Initial version of Swerve Bot Extension
- Enhanced physX
| 175 | Markdown | 10.733333 | 41 | 0.468571 |
RoboEagles4828/2023RobotROS/isaac/omni.isaac.swerve_bot/docs/README.md | # Usage
To enable this extension, go to the Extension Manager menu and enable omni.isaac.swerve_bot extension.
| 113 | Markdown | 21.799996 | 102 | 0.787611 |
RoboEagles4828/offseason2023/docker-compose.yml | version: "3.6"
services:
main_control:
# image: "ghcr.io/roboeagles4828/developer-environment:6"
image: "ghcr.io/roboeagles4828/jetson:3"
network_mode: "host"
environment:
- ROS_DOMAIN_ID=0
- FASTRTPS_DEFAULT_PROFILES_FILE=/usr/local/share/middleware_profiles/rtps_udp_profile.xml
deploy:
restart_policy:
condition: unless-stopped
delay: 2s
max_attempts: 3
window: 120s
entrypoint: ["/bin/bash", "-c", "/opt/workspace/docker/jetson/entrypoint.sh"]
working_dir: /opt/workspace
user: admin
volumes:
- ${HOME}/edna2023:/opt/workspace
zed_cam:
image: ghcr.io/roboeagles4828/jetson-zed:1
network_mode: "host"
privileged: true
runtime: nvidia
environment:
- ROS_DOMAIN_ID=0
- RMW_IMPLEMENTATION=rmw_fastrtps_cpp
- FASTRTPS_DEFAULT_PROFILES_FILE=/usr/local/share/middleware_profiles/rtps_udp_profile.xml
- ROS_NAMESPACE=real
volumes:
- /usr/bin/tegrastats:/usr/bin/tegrastats
- /tmp/argus_socket:/tmp/argus_socket
- /usr/local/cuda-11.4/targets/aarch64-linux/lib/libcusolver.so.11:/usr/local/cuda-11.4/targets/aarch64-linux/lib/libcusolver.so.11
- /usr/local/cuda-11.4/targets/aarch64-linux/lib/libcusparse.so.11:/usr/local/cuda-11.4/targets/aarch64-linux/lib/libcusparse.so.11
- /usr/local/cuda-11.4/targets/aarch64-linux/lib/libcurand.so.10:/usr/local/cuda-11.4/targets/aarch64-linux/lib/libcurand.so.10
- /usr/local/cuda-11.4/targets/aarch64-linux/lib/libnvToolsExt.so:/usr/local/cuda-11.4/targets/aarch64-linux/lib/libnvToolsExt.so
- /usr/local/cuda-11.4/targets/aarch64-linux/lib/libcupti.so.11.4:/usr/local/cuda-11.4/targets/aarch64-linux/lib/libcupti.so.11.4
- /usr/local/cuda-11.4/targets/aarch64-linux/include:/usr/local/cuda-11.4/targets/aarch64-linux/include
- /usr/lib/aarch64-linux-gnu/tegra:/usr/lib/aarch64-linux-gnu/tegra
- /usr/src/jetson_multimedia_api:/usr/src/jetson_multimedia_api
- /opt/nvidia/nsight-systems-cli:/opt/nvidia/nsight-systems-cli
- /opt/nvidia/vpi2:/opt/nvidia/vpi2
- /usr/share/vpi2:/usr/share/vpi2
- /run/jtop.sock:/run/jtop.sock:ro
- /dev/*:/dev/*
- ${HOME}/edna2023/scripts/config/SN39192289.conf:/usr/local/zed/settings/SN39192289.conf
- ${HOME}/edna2023/src/edna_bringup/launch/zed2i.launch.py:/root/ros2_ws/src/zed-ros2-wrapper/zed_wrapper/launch/zed2i.launch.py
depends_on:
- main_control
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: all
capabilities: [gpu]
command: ["ros2", "launch", "zed_wrapper", "zed2i.launch.py"]
| 2,714 | YAML | 45.016948 | 137 | 0.673545 |
RoboEagles4828/offseason2023/ZED.md | # Setting up the ZED Camera with ROS2 Galactic
## Chapter One: Downloading and Installing the Packages
This assumes that you already have a working install of [ROS2 Galactic](https://docs.ros.org/en/galactic/index.html) and the [ZED SDK](https://www.stereolabs.com/developers/release/). You're going to need to go to the [ZED ROS2 Wrapper](https://github.com/stereolabs/zed-ros2-wrapper) and follow the installation insructions to add it here. However, before running `rosdep install`, you'll need to go into the src/ folder and move all of the packages inside of the zed-ros2-wrapper folder into the root src folder.
**WARNING: INCREDIBLY HACKY FIX AHEAD**
*If you're having problems with anything, this is probably the cause of it*
If you try to `colcon build` at this point, you're going to run into some strange error having to do with install/zed_components/lib/libzed_camera_component.so regarding tf2::doTransform. Now, if you're willing to look into why this is erroring, please feel free to fix the code, but if you want a fast and simple solution, then just do this.
Go into src/zed_components/src/zed_camera/src/zed_camera_component.cpp, and scroll down to line 6333. Comment that line out, save the file, and continue on with the rest of this.
Once you've done that, you're also going to need the [ZED ROS2 Examples](https://github.com/stereolabs/zed-ros2-examples) for the 3D bounding boxes to display in RViz2. Go ahead and download their repository, making sure to take the packages out of the folder and put it in src/ directly.
With all of that done, you can finally run `colcon build`.
## Chapter Two: Running RViz2
Now that everything is set up and you ran into no errors whatsoever, you can run it!
Running `ros2 launch zed_wrapper zed2i.launch.py` (make sure to source ros2 and the local install at install/local_setup.bash first) will start a ROS topic publishing out the camera information!
You can also run `ros2 launch zed_display_rviz2 display_zed2i.launch.py` to open RViz2 with the default ZED configuration (useful for the next step).
## Chapter Three: Ordinary Object Detection
If you just want to enable object detection temporarily, then you can run `ros2 service call /zed2i/zed_node/enable_obj_det std_stvs/srv/SetBool data:\ true`. This command will enable object detection for the currently running ROS node.
However, if you want object detection to be on by default, then go into src/zed_wrapper/config/common.yaml, and change line 107 to be true.
(You can also mess with the other object detection settings here).
Now if you open RViz2 with the default ZED settings, you can see the bounding boxes going around the real world things! (You can also add the point cloud from the topic to see it even better).
## Chapter Four: Custom Object Detection
I'm working on it! | 2,820 | Markdown | 77.361109 | 514 | 0.778723 |
RoboEagles4828/offseason2023/README.md | # edna2023
2023 FRC Robot
### Requirements
-------
- RTX Enabled GPU
# Workstation Setup steps
### 1. Install Graphics Drivers
**Install Nvidia Drivers** \
`sudo apt-get install nvidia-driver-525` then restart your machine
### 2. Local Setup
- **Install Docker and Nvidia Docker** \
`./scripts/local-setup.sh` then restart your machine
- **Install Remote Development VS Code Extension** \
Go to extensions and search for Remote Development and click install
- **Reopen in Devcontainer** \
Hit F1 and run the command Reopen in Container and wait for the post install to finsih.
### 3. Isaac Container Setup
- **Create Shaders** \
This uses a lot of cpu resource and can take up to 20min \
`isaac-setup`
- **Launch Isaac** \
`isaac`
### 4. Build ROS2 Packages
- **Build the packages** \
Shortcut: `ctrl + shift + b` \
or \
Terminal: `colcon build --symlink-install`
- **Done with Building ROS2 Packagess**
### 5. (Optional) Omniverse Setup
- **Download Omniverse Launcher** \
https://www.nvidia.com/en-us/omniverse/download/
- **Run Omniverse** \
`chmod +x omniverse-launcher-linux.AppImage` \
`./omniverse-launcher-linux.AppImage`
- **Install Cache and Nucleus Server** \
Wait until both are downloaded and installed.
- **DONE with Omniverse Setup**
# Running Edna
### Inside of Isaac
1. Connect an xbox controller
2. Open Isaac
3. Open Isaac and hit load on the *Import URDF* extension window
4. Press Play on the left hand side
5. Run `launch isaac` inside devcontainer
### In real life (TODO) | 1,516 | Markdown | 21.984848 | 87 | 0.71438 |
RoboEagles4828/offseason2023/src/edna_tests/setup.py | from setuptools import setup
package_name = 'edna_tests'
setup(
name=package_name,
version='0.0.1',
packages=[package_name],
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
],
install_requires=['setuptools'],
zip_safe=True,
maintainer='roboeagles',
maintainer_email='[email protected]',
description='Test robot functions',
license='MIT',
tests_require=['pytest'],
entry_points={
'console_scripts': [
'joint-arm = edna_tests.publish_joint_arm_command:main',
'joint-drive = edna_tests.publish_joint_drive_command:main',
'publish-twist = edna_tests.publish_twist_command:main',
'run-tests = edna_tests.run_tests_command:main',
'arm-tests = edna_tests.arm_tests:main'
],
},
) | 926 | Python | 29.899999 | 72 | 0.602592 |
RoboEagles4828/offseason2023/src/edna_tests/edna_tests/arm_tests.py | import rclpy
import time
from .joint_test import TesterNode
# ROS Topics
SUBSCRIBE_TOPIC_NAME = '/real/real_joint_states'
PUBLISH_TOPIC_NAME = '/real/real_arm_commands'
PUBLISH_INTERVAL = .5 # seconds
# Tolerances
PASS_TOLERANCE = 0.5
WARN_TOLERANCE = 1
TESTS = [
# Here's where you define your tests, in the same style as this one.
# {"positions": [0.0]*6, "time": 3.0},
# Toggle pistons one at a time (to true)
{"positions": [0.0]*4 + [0.0] + [0.0], "time": 10.0},
# {"positions": [0.0]*4 + [0.5] + [0.0], "time": 10.0},
# {"positions": [0.0]*4 + [1.0] + [0.0], "time": 10.0},
# {"positions": [0.0]*6, "time": 10.0},
]
JOINT_NAMES = [
# Pneumatics
'arm_roller_bar_joint',
'top_slider_joint',
'top_gripper_left_arm_joint',
# Wheels
'elevator_center_joint',
'bottom_intake_joint',
]
def main():
rclpy.init()
testerNode = TesterNode(
tests=TESTS,
joint_names=JOINT_NAMES,
joint_range=[8, 14],
pub_topic_name=PUBLISH_TOPIC_NAME,
sub_topic_name=SUBSCRIBE_TOPIC_NAME,
pub_interval=PUBLISH_INTERVAL,
pass_tolerance=PASS_TOLERANCE,
warn_tolerance=WARN_TOLERANCE)
rclpy.spin(testerNode)
if __name__ == '__main__':
main() | 1,267 | Python | 22.481481 | 72 | 0.589582 |
RoboEagles4828/offseason2023/src/edna_tests/edna_tests/run_tests_command.py | import rclpy
from rclpy.node import Node
import math
import time
from rclpy.action import ActionClient
from action_tutorials_interfaces.action import Fibonacci
from sensor_msgs.msg import JointState
import logging
vel_cmds = JointState()
rad = math.pi
vel_cmds.velocity = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
vel_cmds.position = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
vel_cmds.name = [
'front_left_wheel_joint',
'front_left_axle_joint',
'front_right_wheel_joint',
'front_right_axle_joint',
'rear_left_wheel_joint',
'rear_left_axle_joint',
'rear_right_wheel_joint',
'rear_right_axle_joint']
test_return = JointState()
class RunTests(Node):
def __init__(self):
super().__init__('run_tests')
self.publisher_ = self.create_publisher(
JointState,
'real_joint_commands',
10
)
timer_period = 0.1
self.timer = self.create_timer(timer_period, self.timer_callback)
self.i = 0
self.subscription = self.create_subscription(
JointState,
'real_joint_states',
self.listener_callback,
10
)
self.subscription
self.get_logger().info('Testing: ...')
def timer_callback(self):
self.publisher_.publish(vel_cmds)
time.sleep(0.1)
self.i+=1
def listener_callback(self, msg):
test_return = msg
def check(msg, test, test_fail):
count = 0
working = True
for x in msg.velocity:
if (abs(msg.velocity[count] / 1000 - vel_cmds.velocity[count]) > 0.001 or abs(msg.position[count] / 1000 - vel_cmds.position[count]) > 0.001):
working = False
count+=1
if not working:
print(test_fail)
else:
print(test)
def test1(node):
vel_cmds.velocity=[rad, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
t_end = time.time() + 3
while time.time() < t_end:
rclpy.spin_once(node)
time.sleep(1)
check(test_return, 'Test Passed: Front Left Wheel is Spinning!', 'ERROR: Front Left Wheel is NOT spinning, something is wrong!')
def test2(node):
vel_cmds.position=[0.0, rad, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
t_end = time.time() + 3
while time.time() < t_end:
rclpy.spin_once(node)
time.sleep(1)
check(test_return, 'Test Passed: Front Left Axle is Spinning!', 'ERROR: Front Left Axle is NOT spinning, something is wrong!')
def test3(node):
vel_cmds.velocity=[0.0, 0.0, rad, 0.0, 0.0, 0.0, 0.0, 0.0]
t_end = time.time() + 3
while time.time() < t_end:
rclpy.spin_once(node)
time.sleep(1)
check(test_return, 'Test Passed: Front Right Wheel is Spinning!', 'ERROR: Front Right Wheel is NOT spinning, something is wrong!')
def test4(node):
vel_cmds.position=[0.0, 0.0, 0.0, rad, 0.0, 0.0, 0.0, 0.0]
t_end = time.time() + 3
while time.time() < t_end:
rclpy.spin_once(node)
time.sleep(1)
check(test_return, 'Test Passed: Front Right Axle is Spinning!', 'ERROR: Front Right Axle is NOT spinning, something is wrong!')
def test5(node):
vel_cmds.position=[0.0, 0.0, 0.0, 0.0, rad, 0.0, 0.0, 0.0]
t_end = time.time() + 3
while time.time() < t_end:
rclpy.spin_once(node)
time.sleep(1)
check(test_return, 'Test Passed: Rear Left Wheel is Spinning!', 'ERROR: Rear Left Wheel is NOT spinning, something is wrong!')
def test6(node):
vel_cmds.position=[0.0, 0.0, 0.0, 0.0, 0.0, rad, 0.0, 0.0]
t_end = time.time() + 3
while time.time() < t_end:
rclpy.spin_once(node)
time.sleep(1)
check(test_return, 'Test Passed: Rear Left Axle is Spinning!', 'ERROR: Rear Left Axle is NOT spinning, something is wrong!')
def test7(node):
vel_cmds.position=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, rad, 0.0]
t_end = time.time() + 3
while time.time() < t_end:
rclpy.spin_once(node)
time.sleep(1)
check(test_return, 'Test Passed: Rear Right Wheel is Spinning!', 'ERROR: Rear Right Wheel is NOT spinning, something is wrong!')
def test8(node):
vel_cmds.position=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, rad]
t_end = time.time() + 3
while time.time() < t_end:
rclpy.spin_once(node)
time.sleep(1)
check(test_return, 'Test Passed: Rear Right Axle is Spinning!', 'ERROR: Rear Right Axle is NOT spinning, something is wrong!')
def main(args=None):
rclpy.init(args=args)
node = RunTests()
rclpy.spin_once(node)
test1(node)
test2(node)
test3(node)
test4(node)
test5(node)
test6(node)
test7(node)
test8(node)
node.destroy_node()
rclpy.shutdown()
if __name__ == "__main__":
main() | 4,771 | Python | 32.138889 | 154 | 0.590442 |
RoboEagles4828/offseason2023/src/edna_tests/edna_tests/joint_test.py | import time
from rclpy.node import Node
from sensor_msgs.msg import JointState
# COLORS
GREEN = "\033[0;32m"
YELLOW = "\033[1;33m"
RED = "\033[0;31m"
RESET = "\033[0m"
# Default ROS values
SUBSCRIBE_TOPIC_NAME = '/real/real_joint_states'
PUBLISH_INTERVAL = .5 # seconds
# Default Tolerances
PASS_TOLERANCE = 0.5
WARN_TOLERANCE = 1
SCALING_FACTOR_FIX = 10000
class TesterNode(Node):
def __init__(self, tests, joint_names, joint_range, pub_topic_name, sub_topic_name=SUBSCRIBE_TOPIC_NAME, pub_interval=PUBLISH_INTERVAL, pass_tolerance=PASS_TOLERANCE, warn_tolerance=WARN_TOLERANCE):
super().__init__('arm_tester')
# Constructor Arguments
self.TESTS = tests
self.JOINT_NAMES = joint_names
self.JOINT_RANGE = joint_range
self.SUBSCRIBE_TOPIC_NAME = sub_topic_name
self.PUBLISH_TOPIC_NAME = pub_topic_name
self.PUBLISH_INTERVAL = pub_interval
self.PASS_TOLERANCE = pass_tolerance
self.WARN_TOLERANCE = warn_tolerance
self.currentTest = 0
self.testStatus = []
self.lastPositions = [None]*6
self.expectedPositions = self.TESTS[self.currentTest]["positions"]
self.recieving = True
self.startTime = time.time()
self.subscription = self.create_subscription(JointState, self.SUBSCRIBE_TOPIC_NAME, self.recieve, 10)
self.publisher = self.create_publisher(JointState, self.PUBLISH_TOPIC_NAME, 10)
self.publishTimer = self.create_timer(self.PUBLISH_INTERVAL, self.publish)
def publish(self):
msg = JointState()
msg.name = self.JOINT_NAMES
msg.position = self.TESTS[self.currentTest]["positions"]
self.publisher.publish(msg)
self.doTests()
def doTests(self):
if not(self.recieving):
# Start running the next test
self.currentTest += 1
if self.currentTest > len(self.TESTS)-1:
print("\nTests Finished")
for index, test in enumerate(self.testStatus):
print(f"{RED if test['fail'] > 0 else YELLOW if test['warn'] > 0 else GREEN}Test {index} {'FAILED' if test['fail'] > 0 else 'PASSED'} {'with WARNINGS' if test['warn'] > 0 else ''}{RESET}")
exit(0) # shutting down rclpy just kills the node and hangs the process, without actually stopping the program
else:
self.expectedPositions = self.TESTS[self.currentTest]["positions"]
self.lastPositions = [None]*6
self.recieving = True
self.startTime = time.time()
else:
# Check if the current test should end...
timeleft = time.time() - self.startTime
print(f"\rRunning Test {self.currentTest} ({round(self.TESTS[self.currentTest]['time'] - timeleft, 2)}s remaining)", end='')
if time.time() - self.startTime > self.TESTS[self.currentTest]["time"]:
self.recieving = False
self.testStatus.append({"pass": 0, "warn": 0, "fail": 0})
print(f"\rTest {self.currentTest} Completed ")
self.printResults()
print()
def recieve(self, msg : JointState):
if self.recieving:
self.lastPositions = [i / SCALING_FACTOR_FIX for i in msg.position[self.JOINT_RANGE[0]:self.JOINT_RANGE[1]]]
def testFinished(self):
if not self.recieving:
return
self.recieving = False
self.destroy_timer(self.publishTimer)
self.i += 1
def printResults(self):
for index, position in enumerate(self.lastPositions):
if position is None:
print(f"{RED}FAILED: Did not recieve any positions from the robot!{RESET}")
self.testStatus[self.currentTest]["fail"] += 1
continue
difference = abs(self.expectedPositions[index] - position)
if difference == 0:
print(f"{GREEN}Joint {index} PASSED{RESET}")
self.testStatus[self.currentTest]["pass"] += 1
elif difference <= self.PASS_TOLERANCE:
print(f"{GREEN}Difference of {difference} (expected {self.expectedPositions[index]}, got {position}){RESET}")
self.testStatus[self.currentTest]["pass"] += 1
elif difference <= self.WARN_TOLERANCE:
print(f"{YELLOW}Difference of {difference} (expected {self.expectedPositions[index]}, got {position}){RESET}")
self.testStatus[self.currentTest]["warn"] += 1
else:
print(f"{RED}FAILED: Expected position {self.expectedPositions[index]}, got {position}{RESET}")
self.testStatus[self.currentTest]["fail"] += 1 | 4,791 | Python | 43.785046 | 208 | 0.604467 |
RoboEagles4828/offseason2023/src/edna_tests/edna_tests/publish_joint_arm_command.py | import rclpy
from rclpy.node import Node
import math
from sensor_msgs.msg import JointState
class PublishJointCmd(Node):
def __init__(self):
super().__init__('publish_arm_joint_commands')
self.publisher_ = self.create_publisher(JointState, '/real/real_arm_commands', 10)
timer_period = 0.5 # seconds
self.timer = self.create_timer(timer_period, self.timer_callback)
self.i = 0
def timer_callback(self):
# velocity_cmds = JointState()
position_cmds = JointState()
position_cmds.name = [
# Pneumatics
'arm_roller_bar_joint',
'top_slider_joint',
'top_gripper_left_arm_joint',
# Wheels
'elevator_center_joint',
'bottom_intake_joint',
]
# position_cmds.name = []
# rad = math.pi
# velocity_cmds.velocity = [ 0.0 ] * 8
position_cmds.position = [
0.0, # Either a 0 (down) or a 1 (up)
0.0, # Either a 0 (fully back) or a 1 (fully extended)
0.0, # Either a 0 (open) or a 1 (closed)
0.0, # Value between 0.0 (fully back) and 2.0 (fully extended) (will be converted on their end, so just take the motor value and multiply it by two)
0.0 # Value between 0.0 (fully down) and 1.0 (fully up)
]
# position_cmds.position = []
self.publisher_.publish(position_cmds)
# self.publisher_.publish(position_cmds)
self.get_logger().info('Publishing: ...')
self.i += 1
def main(args=None):
rclpy.init(args=args)
node = PublishJointCmd()
rclpy.spin(node)
# Destroy the node explicitly
# (optional - otherwise it will be done automatically
# when the garbage collector destroys the node object)
node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main() | 1,931 | Python | 28.723076 | 165 | 0.568099 |
RoboEagles4828/offseason2023/src/joint_trajectory_teleop/joint_trajectory_teleop/yaml_test.py | import yaml
yaml_path = '/workspaces/edna2023/src/edna_bringup/config/xbox-real.yaml'
with open(yaml_path, 'r') as f:
yaml = yaml.safe_load(f)
yaml = yaml['/*']['joint_trajectory_teleop_node']['ros__parameters']
print(str(yaml['function_mapping']['elevator_loading_station']['button'])) | 291 | Python | 40.71428 | 74 | 0.707904 |
RoboEagles4828/offseason2023/src/joint_trajectory_teleop/joint_trajectory_teleop/joint_trajectory_teleop.py | import rclpy
from rclpy.node import Node
from rclpy.qos import QoSProfile, QoSHistoryPolicy, QoSDurabilityPolicy, QoSReliabilityPolicy
from rclpy import logging
import math
from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint
from sensor_msgs.msg import Joy
import os
from rclpy.qos import QoSDurabilityPolicy, QoSHistoryPolicy, QoSReliabilityPolicy, QoSProfile
import time
import yaml
ENABLE_THROTTLE = True
class toggleButton():
def __init__(self, button, isAxis=False):
self.last_button = 0.0
self.flag = False
self.button = button
self.isAxis = isAxis
def toggle(self, buttons_list):
currentButton = buttons_list[self.button]
if self.isAxis:
# currentButton = currentButton / 10000 if currentButton > 1 else currentButton
if currentButton == -10000.0 and self.last_button != -10000.0:
self.flag = not self.flag
self.last_button = currentButton
return self.flag
else:
self.last_button = currentButton
return self.flag
if currentButton == 1.0 and self.last_button == 0.0:
self.flag = not self.flag
self.last_button = currentButton
return self.flag
else:
self.last_button = currentButton
return self.flag
class PublishTrajectoryMsg(Node):
def __init__(self):
super().__init__('publish_trajectory_msg')
# Joint Map
self.joints = [
'arm_roller_bar_joint',
'elevator_center_joint',
'elevator_outer_1_joint',
'elevator_outer_2_joint',
'top_gripper_right_arm_joint',
'top_gripper_left_arm_joint',
'top_slider_joint',
'bottom_intake_joint',
]
# Publishers and Subscribers
self.publisher_ = self.create_publisher(JointTrajectory, 'joint_trajectory_controller/joint_trajectory', 10)
self.subscriber = self.create_subscription(Joy, 'joy', self.controller_callback, 10)
self.timer_period = 0.5 # seconds
# Load yaml
self.curr_file_path = os.path.abspath(__file__)
self.project_root_path = os.path.abspath(os.path.join(self.curr_file_path, "../../../.."))
self.yaml_path = os.path.join(self.project_root_path, 'src/edna_bringup/config/teleop-control.yaml')
with open(self.yaml_path, 'r') as f:
self.yaml = yaml.safe_load(f)
# Macros
self.functions = [self.elevator_loading_station, self.skis_up, self.elevator_mid_level, self.elevator_high_level, self.top_gripper_control, self.elevator_pivot_control, self.top_slider_control]
# Variables
self.cmds: JointTrajectory = JointTrajectory()
self.position_cmds: JointTrajectoryPoint = JointTrajectoryPoint()
self.position_cmds.positions = [0.0] * len(self.joints)
self.cmds.joint_names = self.joints
self.joint_map = self.yaml['joint_mapping']
self.logger = logging.get_logger('JOINT-TRAJCECTORY-TELEOP')
self.toggle_buttons = {}
self.last_cmd = JointTrajectory()
self.joint_limits = self.yaml["joint_limits"]
# Create Toggle Buttons
for function in self.functions:
buttonName = self.yaml['function_mapping'][function.__name__]['button']
button = self.yaml['controller_mapping'][buttonName]
toggle = self.yaml['function_mapping'][function.__name__]['toggle']
isAxis = "axis" in buttonName.lower()
if toggle:
self.toggle_buttons[function.__name__] = toggleButton(button, isAxis)
def controller_callback(self, joystick: Joy):
for function in self.functions:
buttonName = self.yaml['function_mapping'][function.__name__]['button']
button = self.yaml['controller_mapping'][buttonName]
toggle = self.yaml['function_mapping'][function.__name__]['toggle']
if toggle:
tglBtn = self.toggle_buttons[function.__name__]
if tglBtn.isAxis:
button = tglBtn.toggle(joystick.axes)
else:
button = tglBtn.toggle(joystick.buttons)
else:
button = joystick.buttons[button]
function(button)
self.publisher_.publish(self.cmds)
# Macros
def elevator_loading_station(self, button_val: int):
#TODO: Tweak the values
if button_val == 1.0:
self.position_cmds.positions[int(self.joint_map['elevator_center_joint'])] = 0.056
self.position_cmds.positions[int(self.joint_map['elevator_outer_2_joint'])] = 0.056
self.position_cmds.positions[int(self.joint_map['top_slider_joint'])] = self.joint_limits["top_slider_joint"]["max"]
elif button_val == 0.0:
self.position_cmds.positions[int(self.joint_map['elevator_center_joint'])] = 0.0
self.position_cmds.positions[int(self.joint_map['elevator_outer_2_joint'])] = 0.0
self.position_cmds.positions[int(self.joint_map['top_slider_joint'])] = 0.0
self.cmds.points = [self.position_cmds]
def skis_up(self, button_val: int):
#TODO: Tweak the values
self.position_cmds.positions[int(self.joint_map['bottom_intake_joint'])] = button_val
self.cmds.points = [self.position_cmds]
def elevator_mid_level(self, button_val: int):
#TODO: Tweak the values
if button_val == 1.0:
self.position_cmds.positions[int(self.joint_map['elevator_center_joint'])] = 0.336
self.position_cmds.positions[int(self.joint_map['elevator_outer_2_joint'])] = 0.336
self.position_cmds.positions[int(self.joint_map['top_slider_joint'])] = self.joint_limits["top_slider_joint"]["max"]
self.cmds.points = [self.position_cmds]
def elevator_high_level(self, button_val: int):
#TODO: Tweak the values
if button_val == 1.0:
self.position_cmds.positions[int(self.joint_map['elevator_center_joint'])] = self.joint_limits["elevator_center_joint"]["max"]
self.position_cmds.positions[int(self.joint_map['elevator_outer_2_joint'])] = self.joint_limits["elevator_outer_2_joint"]["max"]
self.position_cmds.positions[int(self.joint_map['top_slider_joint'])] = self.joint_limits["top_slider_joint"]["max"]
elif button_val == 0.0:
self.position_cmds.positions[int(self.joint_map['elevator_outer_1_joint'])] = 0.0
self.cmds.points = [self.position_cmds]
def top_gripper_control(self, button_val: int):
#TODO: Tweak the values
if button_val == 1.0:
self.position_cmds.positions[int(self.joint_map['top_gripper_left_arm_joint'])] = self.joint_limits["top_gripper_left_arm_joint"]["max"]
self.position_cmds.positions[int(self.joint_map['top_gripper_right_arm_joint'])] = self.joint_limits["top_gripper_right_arm_joint"]["max"]
elif button_val == 0.0:
self.position_cmds.positions[int(self.joint_map['top_gripper_left_arm_joint'])] = self.joint_limits["top_gripper_right_arm_joint"]["min"]
self.position_cmds.positions[int(self.joint_map['top_gripper_right_arm_joint'])] = self.joint_limits["top_gripper_right_arm_joint"]["min"]
self.cmds.points = [self.position_cmds]
def elevator_pivot_control(self, button_val: int):
#TODO: Tweak the values
if button_val == 1.0:
self.position_cmds.positions[int(self.joint_map['arm_roller_bar_joint'])] = self.joint_limits["arm_roller_bar_joint"]["max"]
self.position_cmds.positions[int(self.joint_map['elevator_outer_1_joint'])] = self.joint_limits["elevator_outer_1_joint"]["max"]
else:
self.position_cmds.positions[int(self.joint_map['arm_roller_bar_joint'])] = 0.0
self.position_cmds.positions[int(self.joint_map['elevator_outer_1_joint'])] = 0.0
self.cmds.points = [self.position_cmds]
def top_slider_control(self, button_val: int):
#TODO: Tweak the values
if button_val == 1.0:
self.position_cmds.positions[int(self.joint_map['top_slider_joint'])] = self.joint_limits["top_slider_joint"]["max"]
self.cmds.points = [self.position_cmds]
def main(args=None):
rclpy.init(args=args)
node = PublishTrajectoryMsg()
rclpy.spin(node)
node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main() | 8,659 | Python | 40.238095 | 201 | 0.618778 |
RoboEagles4828/offseason2023/src/swerve_hardware/src/isaac_drive.cpp | // Copyright 2021 ros2_control Development Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "swerve_hardware/isaac_drive.hpp"
#include <chrono>
#include <cmath>
#include <limits>
#include <memory>
#include <vector>
#include "hardware_interface/types/hardware_interface_type_values.hpp"
#include "rclcpp/rclcpp.hpp"
#include "swerve_hardware/motion_magic.hpp"
#include "sensor_msgs/msg/joint_state.hpp"
using std::placeholders::_1;
namespace swerve_hardware
{
hardware_interface::CallbackReturn IsaacDriveHardware::on_init(const hardware_interface::HardwareInfo & info)
{
node_ = rclcpp::Node::make_shared("isaac_hardware_interface");
// PUBLISHER SETUP
isaac_publisher_ = node_->create_publisher<sensor_msgs::msg::JointState>(joint_command_topic_, rclcpp::SystemDefaultsQoS());
realtime_isaac_publisher_ = std::make_shared<realtime_tools::RealtimePublisher<sensor_msgs::msg::JointState>>(
isaac_publisher_);
// SUBSCRIBER SETUP
const sensor_msgs::msg::JointState empty_joint_state;
auto qos = rclcpp::QoS(1);
qos.best_effort();
received_joint_msg_ptr_.set(std::make_shared<sensor_msgs::msg::JointState>(empty_joint_state));
isaac_subscriber_ = node_->create_subscription<sensor_msgs::msg::JointState>(joint_state_topic_, qos,
[this](const std::shared_ptr<sensor_msgs::msg::JointState> msg) -> void
{
if (!subscriber_is_active_) {
RCLCPP_WARN( rclcpp::get_logger("isaac_hardware_interface"), "Can't accept new commands. subscriber is inactive");
return;
}
received_joint_msg_ptr_.set(std::move(msg));
});
// COMMON INTERFACE SETUP
if (hardware_interface::SystemInterface::on_init(info) != hardware_interface::CallbackReturn::SUCCESS)
{
return hardware_interface::CallbackReturn::ERROR;
}
// 8 positions states, 4 axle positions 4 wheel positions
hw_positions_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN());
// 8 velocity states, 4 axle velocity 4 wheel velocity
hw_velocities_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN());
// 4 wheel velocity commands
// We will keep this at 8 and make the other 4 zero to keep indexing consistent
hw_command_velocity_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN());
// 4 axle position commands
// We will keep this at 8 and make the other 4 zero to keep indexing consistent
hw_command_position_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN());
joint_types_.resize(info_.joints.size(), "");
motion_magic_.resize(info_.joints.size(), MotionMagic(MAX_ACCELERATION, MAX_VELOCITY));
for (const hardware_interface::ComponentInfo & joint : info_.joints)
{
joint_names_.push_back(joint.name);
if (joint.command_interfaces.size() != 1)
{
RCLCPP_FATAL(
rclcpp::get_logger("IsaacDriveHardware"),
"Joint '%s' has %zu command interfaces found. 1 expected.", joint.name.c_str(),
joint.command_interfaces.size());
return hardware_interface::CallbackReturn::ERROR;
}
if (joint.command_interfaces[0].name != hardware_interface::HW_IF_VELOCITY && joint.command_interfaces[0].name != hardware_interface::HW_IF_POSITION)
{
RCLCPP_FATAL(
rclcpp::get_logger("IsaacDriveHardware"),
"Joint '%s' have %s command interfaces found. '%s' expected.", joint.name.c_str(),
joint.command_interfaces[0].name.c_str(), hardware_interface::HW_IF_VELOCITY);
return hardware_interface::CallbackReturn::ERROR;
}
if (joint.state_interfaces.size() != 2)
{
RCLCPP_FATAL(
rclcpp::get_logger("IsaacDriveHardware"),
"Joint '%s' has %zu state interface. 2 expected.", joint.name.c_str(),
joint.state_interfaces.size());
return hardware_interface::CallbackReturn::ERROR;
}
if (joint.state_interfaces[0].name != hardware_interface::HW_IF_POSITION)
{
RCLCPP_FATAL(
rclcpp::get_logger("IsaacDriveHardware"),
"Joint '%s' have '%s' as first state interface. '%s' expected.", joint.name.c_str(),
joint.state_interfaces[0].name.c_str(), hardware_interface::HW_IF_POSITION);
return hardware_interface::CallbackReturn::ERROR;
}
if (joint.state_interfaces[1].name != hardware_interface::HW_IF_VELOCITY)
{
RCLCPP_FATAL(
rclcpp::get_logger("IsaacDriveHardware"),
"Joint '%s' have '%s' as second state interface. '%s' expected.", joint.name.c_str(),
joint.state_interfaces[1].name.c_str(), hardware_interface::HW_IF_VELOCITY);
return hardware_interface::CallbackReturn::ERROR;
}
}
return hardware_interface::CallbackReturn::SUCCESS;
}
std::vector<hardware_interface::StateInterface> IsaacDriveHardware::export_state_interfaces()
{
// Each joint has 2 state interfaces: position and velocity
std::vector<hardware_interface::StateInterface> state_interfaces;
for (auto i = 0u; i < info_.joints.size(); i++)
{
state_interfaces.emplace_back(hardware_interface::StateInterface(
info_.joints[i].name, hardware_interface::HW_IF_POSITION, &hw_positions_[i]));
state_interfaces.emplace_back(hardware_interface::StateInterface(
info_.joints[i].name, hardware_interface::HW_IF_VELOCITY, &hw_velocities_[i]));
}
return state_interfaces;
}
std::vector<hardware_interface::CommandInterface> IsaacDriveHardware::export_command_interfaces()
{
std::vector<hardware_interface::CommandInterface> command_interfaces;
for (auto i = 0u; i < info_.joints.size(); i++)
{
auto joint = info_.joints[i];
RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Joint Name %s", joint.name.c_str());
if (joint.command_interfaces[0].name == hardware_interface::HW_IF_VELOCITY) {
RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Added Velocity Joint: %s", joint.name.c_str() );
joint_types_[i] = hardware_interface::HW_IF_VELOCITY;
// Add the command interface with a pointer to i of vel commands
command_interfaces.emplace_back(hardware_interface::CommandInterface(
joint.name, hardware_interface::HW_IF_VELOCITY, &hw_command_velocity_[i]));
// Make i of the pos command interface 0.0
hw_command_position_[i] = 0.0;
} else {
RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Added Position Joint: %s", joint.name.c_str() );
joint_types_[i] = hardware_interface::HW_IF_POSITION;
// Add the command interface with a pointer to i of pos commands
command_interfaces.emplace_back(hardware_interface::CommandInterface(
joint.name, hardware_interface::HW_IF_POSITION, &hw_command_position_[i]));
// Make i of the pos command interface 0.0
hw_command_velocity_[i] = 0.0;
}
}
return command_interfaces;
}
hardware_interface::CallbackReturn IsaacDriveHardware::on_activate(const rclcpp_lifecycle::State & /*previous_state*/)
{
RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Activating ...please wait...");
// Set Default Values for State Interface Arrays
for (auto i = 0u; i < hw_positions_.size(); i++)
{
hw_positions_[i] = 0.0;
hw_velocities_[i] = 0.0;
hw_command_velocity_[i] = 0.0;
hw_command_position_[i] = 0.0;
}
subscriber_is_active_ = true;
RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Successfully activated!");
return hardware_interface::CallbackReturn::SUCCESS;
}
hardware_interface::CallbackReturn IsaacDriveHardware::on_deactivate(
const rclcpp_lifecycle::State & /*previous_state*/)
{
RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Deactivating ...please wait...");
subscriber_is_active_ = false;
RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "Successfully deactivated!");
return hardware_interface::CallbackReturn::SUCCESS;
}
// || ||
// \/ THE STUFF THAT MATTERS \/
double IsaacDriveHardware::convertToRosPosition(double isaac_position)
{
// Isaac goes from -2pi to 2pi, we want -pi to pi
if (isaac_position > M_PI) {
return isaac_position - 2.0 * M_PI;
} else if (isaac_position < -M_PI) {
return isaac_position + 2.0 * M_PI;
}
return isaac_position;
}
hardware_interface::return_type IsaacDriveHardware::read(const rclcpp::Time & time, const rclcpp::Duration & /*period*/)
{
rclcpp::spin_some(node_);
std::shared_ptr<sensor_msgs::msg::JointState> last_command_msg;
received_joint_msg_ptr_.get(last_command_msg);
if (last_command_msg == nullptr)
{
RCLCPP_WARN(rclcpp::get_logger("IsaacDriveHardware"), "[%f] Velocity message received was a nullptr.", time.seconds());
return hardware_interface::return_type::ERROR;
}
auto names = last_command_msg->name;
auto positions = last_command_msg->position;
auto velocities = last_command_msg->velocity;
for (auto i = 0u; i < joint_names_.size(); i++) {
for (auto j = 0u; j < names.size(); j++) {
if (strcmp(names[j].c_str(), info_.joints[i].name.c_str()) == 0) {
hw_positions_[i] = convertToRosPosition(positions[j]);
hw_velocities_[i] = (float)velocities[j];
break;
}
}
}
return hardware_interface::return_type::OK;
}
hardware_interface::return_type swerve_hardware::IsaacDriveHardware::write(const rclcpp::Time & /*time*/, const rclcpp::Duration & period)
{
// Calculate Axle Velocities using motion magic
double dt = period.seconds();
for (auto i = 0u; i < joint_names_.size(); i++) {
if (joint_names_[i].find("axle") != std::string::npos) {
auto vel = motion_magic_[i].getNextVelocity(hw_command_position_[i], hw_positions_[i], hw_velocities_[i], dt);
// RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Current: %f, Target: %f Vel: %f", hw_positions_[i], hw_command_position_[i], vel);
hw_command_velocity_[i] = vel;
}
if (joint_names_[i] == "front_left_wheel_joint") {
auto& clk = *node_->get_clock();
RCLCPP_INFO_THROTTLE(rclcpp::get_logger("IsaacDriveHardware"), clk, 2000,
"Joint: %s Current Vel: %f Target Vel: %f Pos: %f", joint_names_[i].c_str(), hw_velocities_[i], hw_command_velocity_[i], hw_positions_[i]);
}
}
// Publish to Isaac
if (realtime_isaac_publisher_->trylock()) {
auto & realtime_isaac_command_ = realtime_isaac_publisher_->msg_;
realtime_isaac_command_.header.stamp = node_->get_clock()->now();
realtime_isaac_command_.name = joint_names_;
realtime_isaac_command_.velocity = hw_command_velocity_;
realtime_isaac_command_.position = empty_;
realtime_isaac_publisher_->unlockAndPublish();
}
rclcpp::spin_some(node_);
if (realtime_isaac_publisher_->trylock()) {
auto & realtime_isaac_command_ = realtime_isaac_publisher_->msg_;
realtime_isaac_command_.header.stamp = node_->get_clock()->now();
realtime_isaac_command_.name = joint_names_;
realtime_isaac_command_.velocity = empty_;
realtime_isaac_command_.position = hw_command_position_;
realtime_isaac_publisher_->unlockAndPublish();
}
rclcpp::spin_some(node_);
return hardware_interface::return_type::OK;
}
} // namespace swerve_hardware
#include "pluginlib/class_list_macros.hpp"
PLUGINLIB_EXPORT_CLASS(
swerve_hardware::IsaacDriveHardware, hardware_interface::SystemInterface) | 11,781 | C++ | 37.006451 | 153 | 0.683643 |
RoboEagles4828/offseason2023/src/swerve_hardware/src/test_drive.cpp | // Copyright 2021 ros2_control Development Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "swerve_hardware/test_drive.hpp"
#include <chrono>
#include <cmath>
#include <limits>
#include <memory>
#include <vector>
#include "hardware_interface/types/hardware_interface_type_values.hpp"
#include "swerve_hardware/motion_magic.hpp"
#include "rclcpp/rclcpp.hpp"
using std::placeholders::_1;
namespace swerve_hardware
{
hardware_interface::CallbackReturn TestDriveHardware::on_init(const hardware_interface::HardwareInfo & info)
{
// COMMON INTERFACE SETUP
if (hardware_interface::SystemInterface::on_init(info) != hardware_interface::CallbackReturn::SUCCESS)
{
return hardware_interface::CallbackReturn::ERROR;
}
// 8 positions states, 4 axle positions 4 wheel positions
hw_positions_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN());
// 8 velocity states, 4 axle velocity 4 wheel velocity
hw_velocities_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN());
// 4 wheel velocity commands
// We will keep this at 8 and make the other 4 zero to keep indexing consistent
hw_command_velocity_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN());
// 4 axle position commands
// We will keep this at 8 and make the other 4 zero to keep indexing consistent
hw_command_position_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN());
joint_types_.resize(info_.joints.size(), "");
motion_magic_.resize(info_.joints.size(), MotionMagic(MAX_ACCELERATION, MAX_VELOCITY));
for (const hardware_interface::ComponentInfo & joint : info_.joints)
{
joint_names_.push_back(joint.name);
if (joint.command_interfaces.size() != 1)
{
RCLCPP_FATAL(
rclcpp::get_logger("TestDriveHardware"),
"Joint '%s' has %zu command interfaces found. 1 expected.", joint.name.c_str(),
joint.command_interfaces.size());
return hardware_interface::CallbackReturn::ERROR;
}
if (joint.command_interfaces[0].name != hardware_interface::HW_IF_VELOCITY && joint.command_interfaces[0].name != hardware_interface::HW_IF_POSITION)
{
RCLCPP_FATAL(
rclcpp::get_logger("TestDriveHardware"),
"Joint '%s' have %s command interfaces found. '%s' expected.", joint.name.c_str(),
joint.command_interfaces[0].name.c_str(), hardware_interface::HW_IF_VELOCITY);
return hardware_interface::CallbackReturn::ERROR;
}
if (joint.state_interfaces.size() != 2)
{
RCLCPP_FATAL(
rclcpp::get_logger("TestDriveHardware"),
"Joint '%s' has %zu state interface. 2 expected.", joint.name.c_str(),
joint.state_interfaces.size());
return hardware_interface::CallbackReturn::ERROR;
}
if (joint.state_interfaces[0].name != hardware_interface::HW_IF_POSITION)
{
RCLCPP_FATAL(
rclcpp::get_logger("TestDriveHardware"),
"Joint '%s' have '%s' as first state interface. '%s' expected.", joint.name.c_str(),
joint.state_interfaces[0].name.c_str(), hardware_interface::HW_IF_POSITION);
return hardware_interface::CallbackReturn::ERROR;
}
if (joint.state_interfaces[1].name != hardware_interface::HW_IF_VELOCITY)
{
RCLCPP_FATAL(
rclcpp::get_logger("TestDriveHardware"),
"Joint '%s' have '%s' as second state interface. '%s' expected.", joint.name.c_str(),
joint.state_interfaces[1].name.c_str(), hardware_interface::HW_IF_VELOCITY);
return hardware_interface::CallbackReturn::ERROR;
}
}
return hardware_interface::CallbackReturn::SUCCESS;
}
std::vector<hardware_interface::StateInterface> TestDriveHardware::export_state_interfaces()
{
// Each joint has 2 state interfaces: position and velocity
std::vector<hardware_interface::StateInterface> state_interfaces;
for (auto i = 0u; i < info_.joints.size(); i++)
{
state_interfaces.emplace_back(hardware_interface::StateInterface(
info_.joints[i].name, hardware_interface::HW_IF_POSITION, &hw_positions_[i]));
state_interfaces.emplace_back(hardware_interface::StateInterface(
info_.joints[i].name, hardware_interface::HW_IF_VELOCITY, &hw_velocities_[i]));
}
return state_interfaces;
}
std::vector<hardware_interface::CommandInterface> TestDriveHardware::export_command_interfaces()
{
std::vector<hardware_interface::CommandInterface> command_interfaces;
for (auto i = 0u; i < info_.joints.size(); i++)
{
auto joint = info_.joints[i];
RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Joint Name %s", joint.name.c_str());
if (joint.command_interfaces[0].name == hardware_interface::HW_IF_VELOCITY) {
RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Added Velocity Joint: %s", joint.name.c_str() );
joint_types_[i] = hardware_interface::HW_IF_VELOCITY;
// Add the command interface with a pointer to i of vel commands
command_interfaces.emplace_back(hardware_interface::CommandInterface(
joint.name, hardware_interface::HW_IF_VELOCITY, &hw_command_velocity_[i]));
// Make i of the pos command interface 0.0
hw_command_position_[i] = 0.0;
} else {
RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Added Position Joint: %s", joint.name.c_str() );
joint_types_[i] = hardware_interface::HW_IF_POSITION;
// Add the command interface with a pointer to i of pos commands
command_interfaces.emplace_back(hardware_interface::CommandInterface(
joint.name, hardware_interface::HW_IF_POSITION, &hw_command_position_[i]));
// Make i of the pos command interface 0.0
hw_command_velocity_[i] = 0.0;
}
}
return command_interfaces;
}
hardware_interface::CallbackReturn TestDriveHardware::on_activate(const rclcpp_lifecycle::State & /*previous_state*/)
{
RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Activating ...please wait...");
// Set Default Values for State Interface Arrays
for (auto i = 0u; i < hw_positions_.size(); i++)
{
hw_positions_[i] = 0.0;
hw_velocities_[i] = 0.0;
hw_command_velocity_[i] = 0.0;
hw_command_position_[i] = 0.0;
}
RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Successfully activated!");
return hardware_interface::CallbackReturn::SUCCESS;
}
hardware_interface::CallbackReturn TestDriveHardware::on_deactivate(const rclcpp_lifecycle::State & /*previous_state*/)
{
RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Deactivating ...please wait...");
RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Successfully deactivated!");
return hardware_interface::CallbackReturn::SUCCESS;
}
// || ||
// \/ THE STUFF THAT MATTERS \/
hardware_interface::return_type TestDriveHardware::read(const rclcpp::Time & /*time*/, const rclcpp::Duration & period)
{
// Dumb Pass Through
// If you give the command for x velocity then the state is x velocity
// Loop through each joint name
// Check if joint name is in velocity command map
// If it is, use the index from the map to get the value in the velocity array
// If velocity not in map, set velocity value to 0
// Perform the same for position
double dt = period.seconds();
for (auto i = 0u; i < joint_names_.size(); i++)
{
if (joint_types_[i] == hardware_interface::HW_IF_VELOCITY)
{
hw_velocities_[i] = hw_command_velocity_[i];
hw_positions_[i] = hw_positions_[i] + dt * hw_velocities_[i];
}
else if (joint_types_[i] == hardware_interface::HW_IF_POSITION)
{
auto vel = motion_magic_[i].getNextVelocity(hw_command_position_[i], hw_positions_[i], hw_velocities_[i], dt);
// RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Current: %f, Target: %f Vel: %f", hw_positions_[i], hw_command_position_[i], vel);
hw_velocities_[i] = vel;
hw_positions_[i] = hw_positions_[i] + hw_velocities_[i] * dt;
// Test without any velocity smoothing
// RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Cmd: %f Name: %s", hw_command_position_[i], joint_names_[i].c_str());
// hw_velocities_[i] = 0.0;
// hw_positions_[i] = hw_command_position_[i];
}
}
return hardware_interface::return_type::OK;
}
hardware_interface::return_type TestDriveHardware::write(const rclcpp::Time & /*time*/, const rclcpp::Duration & /*period*/)
{
// Do Nothing
// Uncomment below if you want verbose messages for debugging.
// for (auto i = 0u; i < hw_command_velocity_.size(); i++)
// {
// RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "Wheel %u Velocity: %f", i, hw_command_velocity_[i]);
// }
// RCLCPP_INFO(rclcpp::get_logger("TestDriveHardware"), "[%f] Joint 2 Position: %f", time.seconds(), hw_command_position_[2]);
return hardware_interface::return_type::OK;
}
} // namespace swerve_hardware
#include "pluginlib/class_list_macros.hpp"
PLUGINLIB_EXPORT_CLASS(
swerve_hardware::TestDriveHardware, hardware_interface::SystemInterface) | 9,533 | C++ | 37.59919 | 153 | 0.683625 |
RoboEagles4828/offseason2023/src/swerve_hardware/src/motion_magic.cpp | #include "swerve_hardware/motion_magic.hpp"
#include <chrono>
#include <cmath>
#include <limits>
#include <memory>
#include <vector>
#include <ostream>
#include <iostream>
namespace swerve_hardware
{
MotionMagic::MotionMagic(double maxAcceleration, double maxVelocity)
{
this->MAX_ACCELERATION = maxAcceleration;
this->MAX_VELOCITY = maxVelocity;
}
double MotionMagic::getPositionDifference(double targetPosition, double sensorPosition) {
double copy_targetPosition = targetPosition;
double difference = copy_targetPosition - sensorPosition;
if (difference > M_PI) {
copy_targetPosition -= 2 * M_PI;
} else if (difference < -M_PI) {
copy_targetPosition += 2 * M_PI;
}
return std::fmod(copy_targetPosition - sensorPosition, M_PI);
}
// (maxV - curr)t1 + curr
// (curr - maxV)tf + b = 0
// 2 10
// 4(t1)
double MotionMagic::getNextVelocity(const double targetPosition, const double sensorPosition, const double sensorVelocity, const double dt) {
// method 0
double error = getPositionDifference(targetPosition, sensorPosition);
double absError = std::abs(error);
if (targetPosition != prevTargetPosition) {
totalDistance = absError;
prevTargetPosition = targetPosition;
}
if (absError < tolerance) {
return 0.0;
}
double dir = 1.0;
if (error < 0.0) {
dir = -1.0;
}
if (absError <= rampWindow1) {
return velocityInRampWindow1 * dir;
} else if (absError <= rampWindow2) {
return velocityInRampWindow2 * dir;
} else {
return velocityInCruiseWindow * dir;
}
//method 1
// double displacement = std::abs(getPositionDifference(targetPosition, sensorPosition));
// double dir = targetPosition - sensorPosition;
// double slow_down_dist = (MAX_JERK/6) * pow(2*sensorVelocity/MAX_JERK, 1.5);
// if(std::abs(displacement - 0.0) <= tolerance) return 0.0;
// if(dir > 0) {
// if(displacement <= slow_down_dist) return std::max(sensorVelocity - dt * dt * MAX_JERK, -1*MAX_VELOCITY);
// // std::cout<<std::min(sensorVelocity + dt * dt * MAX_JERK, MAX_VELOCITY);
// else return std::min(sensorVelocity + dt * dt * MAX_JERK, MAX_VELOCITY);
// } else {
// if(displacement <= slow_down_dist) return std::min(sensorVelocity + dt * dt * MAX_JERK, MAX_VELOCITY);
// else return std::max(sensorVelocity - dt * dt * MAX_JERK, -1*MAX_VELOCITY);
// }
}
} // namespace swerve_hardware
| 2,741 | C++ | 33.70886 | 145 | 0.594673 |
RoboEagles4828/offseason2023/src/swerve_hardware/src/real_drive.cpp | // Copyright 2021 ros2_control Development Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "swerve_hardware/real_drive.hpp"
#include <chrono>
#include <cmath>
#include <limits>
#include <memory>
#include <vector>
#include "hardware_interface/types/hardware_interface_type_values.hpp"
#include "rclcpp/rclcpp.hpp"
#include "swerve_hardware/motion_magic.hpp"
#include "sensor_msgs/msg/joint_state.hpp"
using std::placeholders::_1;
namespace swerve_hardware
{
double RealDriveHardware::parse_double(const std::string & text)
{
return std::atof(text.c_str());
}
bool RealDriveHardware::parse_bool(const std::string & text)
{
if(strcmp(text.c_str(), "true") == 0) {
return true;
} else {
return false;
}
}
hardware_interface::CallbackReturn RealDriveHardware::on_init(const hardware_interface::HardwareInfo & info)
{
node_ = rclcpp::Node::make_shared("isaac_hardware_interface");
// PUBLISHER SETUP
real_publisher_ = node_->create_publisher<sensor_msgs::msg::JointState>(joint_command_topic_, rclcpp::SystemDefaultsQoS());
realtime_real_publisher_ = std::make_shared<realtime_tools::RealtimePublisher<sensor_msgs::msg::JointState>>(
real_publisher_);
real_arm_publisher_ = node_->create_publisher<sensor_msgs::msg::JointState>(joint_arm_command_topic_, rclcpp::SystemDefaultsQoS());
realtime_real_arm_publisher_ = std::make_shared<realtime_tools::RealtimePublisher<sensor_msgs::msg::JointState>>(
real_arm_publisher_);
// SUBSCRIBER SETUP
const sensor_msgs::msg::JointState empty_joint_state;
auto qos = rclcpp::QoS(1);
qos.best_effort();
received_joint_msg_ptr_.set(std::make_shared<sensor_msgs::msg::JointState>(empty_joint_state));
real_subscriber_ = node_->create_subscription<sensor_msgs::msg::JointState>(joint_state_topic_, qos,
[this](const std::shared_ptr<sensor_msgs::msg::JointState> msg) -> void
{
if (!subscriber_is_active_) {
RCLCPP_WARN( rclcpp::get_logger("isaac_hardware_interface"), "Can't accept new commands. subscriber is inactive");
return;
}
received_joint_msg_ptr_.set(std::move(msg));
});
// COMMON INTERFACE SETUP
if (hardware_interface::SystemInterface::on_init(info) != hardware_interface::CallbackReturn::SUCCESS)
{
return hardware_interface::CallbackReturn::ERROR;
}
// GLOBAL VECTOR SETUP
hw_positions_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN());
hw_velocities_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN());
hw_command_velocity_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN());
hw_command_position_.resize(info_.joints.size(), std::numeric_limits<double>::quiet_NaN());
joint_types_.resize(info_.joints.size(), "");
// JOINT GROUPS
for (auto i = 0u; i < info_.joints.size(); ++i)
{
const auto & joint = info_.joints.at(i);
bool use_percent = false;
double max = parse_double(joint.command_interfaces[0].max);
double min = parse_double(joint.command_interfaces[0].min);
auto param_percent_it = joint.parameters.find("percent");
if (param_percent_it != joint.parameters.end()) {
use_percent = parse_bool(joint.parameters.at("percent"));
}
// Mimics
if (joint.parameters.find("mimic") != joint.parameters.cend())
{
const auto mimicked_joint_it = std::find_if(
info_.joints.begin(), info_.joints.end(),
[&mimicked_joint =
joint.parameters.at("mimic")](const hardware_interface::ComponentInfo & joint_info)
{ return joint_info.name == mimicked_joint; });
if (mimicked_joint_it == info_.joints.cend())
{
throw std::runtime_error(
std::string("Mimicked joint '") + joint.parameters.at("mimic") + "' not found");
}
MimicJoint mimic_joint;
mimic_joint.joint_index = i;
mimic_joint.mimicked_joint_index = std::distance(info_.joints.begin(), mimicked_joint_it);
// Multiplier and offset
auto param_mult_it = joint.parameters.find("multiplier");
if (param_mult_it != joint.parameters.end()) {
mimic_joint.multiplier = parse_double(joint.parameters.at("multiplier"));
}
auto param_off_it = joint.parameters.find("offset");
if (param_off_it != joint.parameters.end()) {
mimic_joint.offset = parse_double(joint.parameters.at("offset"));
}
mimic_joints_.push_back(mimic_joint);
}
//
else if (joint.parameters.find("arm_group") != joint.parameters.cend())
{
JointGroupMember member;
member.joint_index = i;
member.joint_name = joint.name;
member.percent = use_percent;
member.max = max;
member.min = min;
arm_names_output_.push_back(joint.name);
arm_joints_.push_back(member);
} else {
JointGroupMember member;
member.joint_index = i;
member.joint_name = joint.name;
member.percent = use_percent;
member.max = max;
member.min = min;
drive_names_output_.push_back(joint.name);
drive_joints_.push_back(member);
}
}
hw_command_arm_velocity_output_.resize(arm_joints_.size(), std::numeric_limits<double>::quiet_NaN());
hw_command_arm_position_output_.resize(arm_joints_.size(), std::numeric_limits<double>::quiet_NaN());
hw_command_drive_velocity_output_.resize(drive_joints_.size(), std::numeric_limits<double>::quiet_NaN());
hw_command_drive_position_output_.resize(drive_joints_.size(), std::numeric_limits<double>::quiet_NaN());
// Check that the info we were passed makes sense
for (const hardware_interface::ComponentInfo & joint : info_.joints)
{
joint_names_.push_back(joint.name);
if (joint.command_interfaces.size() != 1)
{
RCLCPP_FATAL(
rclcpp::get_logger("RealDriveHardware"),
"Joint '%s' has %zu command interfaces found. 1 expected.", joint.name.c_str(),
joint.command_interfaces.size());
return hardware_interface::CallbackReturn::ERROR;
}
if (joint.command_interfaces[0].name != hardware_interface::HW_IF_VELOCITY && joint.command_interfaces[0].name != hardware_interface::HW_IF_POSITION)
{
RCLCPP_FATAL(
rclcpp::get_logger("RealDriveHardware"),
"Joint '%s' have %s command interfaces found. '%s' expected.", joint.name.c_str(),
joint.command_interfaces[0].name.c_str(), hardware_interface::HW_IF_VELOCITY);
return hardware_interface::CallbackReturn::ERROR;
}
if (joint.state_interfaces.size() != 2)
{
RCLCPP_FATAL(
rclcpp::get_logger("RealDriveHardware"),
"Joint '%s' has %zu state interface. 2 expected.", joint.name.c_str(),
joint.state_interfaces.size());
return hardware_interface::CallbackReturn::ERROR;
}
if (joint.state_interfaces[0].name != hardware_interface::HW_IF_POSITION)
{
RCLCPP_FATAL(
rclcpp::get_logger("RealDriveHardware"),
"Joint '%s' have '%s' as first state interface. '%s' expected.", joint.name.c_str(),
joint.state_interfaces[0].name.c_str(), hardware_interface::HW_IF_POSITION);
return hardware_interface::CallbackReturn::ERROR;
}
if (joint.state_interfaces[1].name != hardware_interface::HW_IF_VELOCITY)
{
RCLCPP_FATAL(
rclcpp::get_logger("RealDriveHardware"),
"Joint '%s' have '%s' as second state interface. '%s' expected.", joint.name.c_str(),
joint.state_interfaces[1].name.c_str(), hardware_interface::HW_IF_VELOCITY);
return hardware_interface::CallbackReturn::ERROR;
}
}
return hardware_interface::CallbackReturn::SUCCESS;
}
std::vector<hardware_interface::StateInterface> RealDriveHardware::export_state_interfaces()
{
// Each joint has 2 state interfaces: position and velocity
std::vector<hardware_interface::StateInterface> state_interfaces;
for (auto i = 0u; i < info_.joints.size(); i++)
{
state_interfaces.emplace_back(hardware_interface::StateInterface(
info_.joints[i].name, hardware_interface::HW_IF_POSITION, &hw_positions_[i]));
state_interfaces.emplace_back(hardware_interface::StateInterface(
info_.joints[i].name, hardware_interface::HW_IF_VELOCITY, &hw_velocities_[i]));
}
return state_interfaces;
}
std::vector<hardware_interface::CommandInterface> RealDriveHardware::export_command_interfaces()
{
std::vector<hardware_interface::CommandInterface> command_interfaces;
for (auto i = 0u; i < info_.joints.size(); i++)
{
auto joint = info_.joints[i];
RCLCPP_INFO(rclcpp::get_logger("RealDriveHardware"), "Joint Name %s", joint.name.c_str());
if (joint.command_interfaces[0].name == hardware_interface::HW_IF_VELOCITY) {
RCLCPP_INFO(rclcpp::get_logger("RealDriveHardware"), "Added Velocity Joint: %s", joint.name.c_str() );
joint_types_[i] = hardware_interface::HW_IF_VELOCITY;
// Add the command interface with a pointer to i of vel commands
command_interfaces.emplace_back(hardware_interface::CommandInterface(
joint.name, hardware_interface::HW_IF_VELOCITY, &hw_command_velocity_[i]));
// Make i of the pos command interface 0.0
hw_command_position_[i] = 0.0;
} else {
RCLCPP_INFO(rclcpp::get_logger("RealDriveHardware"), "Added Position Joint: %s", joint.name.c_str() );
joint_types_[i] = hardware_interface::HW_IF_POSITION;
// Add the command interface with a pointer to i of pos commands
command_interfaces.emplace_back(hardware_interface::CommandInterface(
joint.name, hardware_interface::HW_IF_POSITION, &hw_command_position_[i]));
// Make i of the pos command interface 0.0
hw_command_velocity_[i] = 0.0;
}
}
return command_interfaces;
}
hardware_interface::CallbackReturn RealDriveHardware::on_activate(const rclcpp_lifecycle::State & /*previous_state*/)
{
RCLCPP_INFO(rclcpp::get_logger("RealDriveHardware"), "Activating ...please wait...");
// Set Default Values for State Interface Arrays
for (auto i = 0u; i < hw_positions_.size(); i++)
{
hw_positions_[i] = 0.0;
hw_velocities_[i] = 0.0;
hw_command_velocity_[i] = 0.0;
hw_command_position_[i] = 0.0;
}
subscriber_is_active_ = true;
RCLCPP_INFO(rclcpp::get_logger("RealDriveHardware"), "Successfully activated!");
return hardware_interface::CallbackReturn::SUCCESS;
}
hardware_interface::CallbackReturn RealDriveHardware::on_deactivate(
const rclcpp_lifecycle::State & /*previous_state*/)
{
RCLCPP_INFO(rclcpp::get_logger("RealDriveHardware"), "Deactivating ...please wait...");
subscriber_is_active_ = false;
RCLCPP_INFO(rclcpp::get_logger("RealDriveHardware"), "Successfully deactivated!");
return hardware_interface::CallbackReturn::SUCCESS;
}
// || ||
// \/ THE STUFF THAT MATTERS \/
double RealDriveHardware::convertToRosPosition(double real_position)
{
// Convert the rio integer that has been scaled
real_position /= RIO_CONVERSION_FACTOR;
// Just in case we get values we are not expecting
real_position = std::fmod(real_position, 2.0 * M_PI);
// Real goes from -2pi to 2pi, we want -pi to pi
if (real_position > M_PI)
{
real_position -= 2.0 * M_PI;
}
return real_position;
}
double RealDriveHardware::convertToRosVelocity(double real_velocity)
{
// Convert the rio integer that has been scaled
return real_velocity / RIO_CONVERSION_FACTOR;
}
hardware_interface::return_type RealDriveHardware::read(const rclcpp::Time &time, const rclcpp::Duration & /*period*/)
{
rclcpp::spin_some(node_);
std::shared_ptr<sensor_msgs::msg::JointState> last_command_msg;
received_joint_msg_ptr_.get(last_command_msg);
if (last_command_msg == nullptr)
{
RCLCPP_WARN(rclcpp::get_logger("IsaacDriveHardware"), "[%f] Velocity message received was a nullptr.", time.seconds());
return hardware_interface::return_type::ERROR;
}
auto names = last_command_msg->name;
auto positions = last_command_msg->position;
auto velocities = last_command_msg->velocity;
// Match Arm and Drive Joints
for (auto i = 0u; i < names.size(); i++) {
for (const auto & arm_joint : arm_joints_)
{
if (strcmp(names[i].c_str(), arm_joint.joint_name.c_str()) == 0) {
if (arm_joint.percent) {
double scale = arm_joint.max - arm_joint.min;
hw_positions_[arm_joint.joint_index] = convertToRosPosition(positions[i] * scale + arm_joint.min);
hw_velocities_[arm_joint.joint_index] = convertToRosVelocity((float)velocities[i] * scale);
} else {
hw_positions_[arm_joint.joint_index] = convertToRosPosition(positions[i]);
hw_velocities_[arm_joint.joint_index] = convertToRosVelocity((float)velocities[i]);
}
break;
}
}
for (const auto & drive_joint : drive_joints_)
{
if (strcmp(names[i].c_str(), drive_joint.joint_name.c_str()) == 0) {
hw_positions_[drive_joint.joint_index] = convertToRosPosition(positions[i]);
hw_velocities_[drive_joint.joint_index] = convertToRosVelocity((float)velocities[i]);
break;
}
}
}
// Apply Mimic Joints
for (const auto & mimic_joint : mimic_joints_)
{
hw_positions_[mimic_joint.joint_index] = hw_positions_[mimic_joint.mimicked_joint_index] * mimic_joint.multiplier + mimic_joint.offset;
hw_velocities_[mimic_joint.joint_index] = hw_velocities_[mimic_joint.mimicked_joint_index] * mimic_joint.multiplier;
}
return hardware_interface::return_type::OK;
}
hardware_interface::return_type swerve_hardware::RealDriveHardware::write(const rclcpp::Time & /*time*/, const rclcpp::Duration & /*period*/)
{
// convertToRealPositions(hw_command_position_);
// convertToRealElevatorPosition();
// Publish to Real
for (auto i = 0u; i < drive_joints_.size(); ++i)
{
auto joint = drive_joints_[i];
hw_command_drive_velocity_output_[i] = hw_command_velocity_[joint.joint_index];
hw_command_drive_position_output_[i] = hw_command_position_[joint.joint_index];
}
for (auto i = 0u; i < arm_joints_.size(); ++i)
{
auto joint = arm_joints_[i];
hw_command_arm_velocity_output_[i] = hw_command_velocity_[joint.joint_index];
hw_command_arm_position_output_[i] = hw_command_position_[joint.joint_index];
}
if (realtime_real_publisher_->trylock())
{
auto &realtime_real_command_ = realtime_real_publisher_->msg_;
realtime_real_command_.header.stamp = node_->get_clock()->now();
realtime_real_command_.name = drive_names_output_;
realtime_real_command_.velocity = hw_command_drive_velocity_output_;
realtime_real_command_.position = hw_command_drive_position_output_;
realtime_real_publisher_->unlockAndPublish();
}
if (realtime_real_arm_publisher_->trylock())
{
auto &realtime_real_arm_command_ = realtime_real_arm_publisher_->msg_;
realtime_real_arm_command_.header.stamp = node_->get_clock()->now();
realtime_real_arm_command_.name = arm_names_output_;
realtime_real_arm_command_.velocity = hw_command_arm_velocity_output_;
realtime_real_arm_command_.position = hw_command_arm_position_output_;
realtime_real_arm_publisher_->unlockAndPublish();
}
rclcpp::spin_some(node_);
return hardware_interface::return_type::OK;
}
} // namespace swerve_hardware
#include "pluginlib/class_list_macros.hpp"
PLUGINLIB_EXPORT_CLASS(
swerve_hardware::RealDriveHardware, hardware_interface::SystemInterface) | 16,614 | C++ | 37.820093 | 155 | 0.648429 |
RoboEagles4828/offseason2023/src/swerve_hardware/include/swerve_hardware/real_drive.hpp | // Copyright 2021 ros2_control Development Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef SWERVE_HARDWARE__REAL_DRIVE_HPP_
#define SWERVE_HARDWARE__REAL_DRIVE_HPP_
#include <memory>
#include <string>
#include <vector>
#include <map>
#include "hardware_interface/handle.hpp"
#include "hardware_interface/hardware_info.hpp"
#include "hardware_interface/system_interface.hpp"
#include "hardware_interface/types/hardware_interface_return_values.hpp"
#include "rclcpp/clock.hpp"
#include "rclcpp/duration.hpp"
#include "rclcpp/macros.hpp"
#include "rclcpp/time.hpp"
#include "rclcpp_lifecycle/node_interfaces/lifecycle_node_interface.hpp"
#include "rclcpp_lifecycle/state.hpp"
#include "rclcpp/rclcpp.hpp"
#include "sensor_msgs/msg/joint_state.hpp"
#include "realtime_tools/realtime_box.h"
#include "realtime_tools/realtime_buffer.h"
#include "realtime_tools/realtime_publisher.h"
#include "swerve_hardware/visibility_control.h"
namespace swerve_hardware
{
class RealDriveHardware : public hardware_interface::SystemInterface
{
public:
RCLCPP_SHARED_PTR_DEFINITIONS(RealDriveHardware)
SWERVE_HARDWARE_PUBLIC
hardware_interface::CallbackReturn on_init(const hardware_interface::HardwareInfo & info) override;
SWERVE_HARDWARE_PUBLIC
std::vector<hardware_interface::StateInterface> export_state_interfaces() override;
SWERVE_HARDWARE_PUBLIC
std::vector<hardware_interface::CommandInterface> export_command_interfaces() override;
SWERVE_HARDWARE_PUBLIC
hardware_interface::CallbackReturn on_activate(const rclcpp_lifecycle::State & previous_state) override;
SWERVE_HARDWARE_PUBLIC
hardware_interface::CallbackReturn on_deactivate(const rclcpp_lifecycle::State & previous_state) override;
SWERVE_HARDWARE_PUBLIC
hardware_interface::return_type read(const rclcpp::Time & time, const rclcpp::Duration & period) override;
SWERVE_HARDWARE_PUBLIC
hardware_interface::return_type write(const rclcpp::Time & time, const rclcpp::Duration & period) override;
private:
double RIO_CONVERSION_FACTOR = 10000.0;
// Store the command for the simulated robot
std::vector<double> hw_command_velocity_;
std::vector<double> hw_command_position_;
// Output Topic Vectors
std::vector<std::string> arm_names_output_;
std::vector<double> hw_command_arm_velocity_output_;
std::vector<double> hw_command_arm_position_output_;
std::vector<std::string> drive_names_output_;
std::vector<double> hw_command_drive_velocity_output_;
std::vector<double> hw_command_drive_position_output_;
// The state vectors
std::vector<double> hw_positions_;
std::vector<double> hw_velocities_;
std::vector<double> hw_positions_input_;
std::vector<double> hw_velocities_input_;
// Mimic Joints for joints not controlled by the real robot
struct MimicJoint
{
std::size_t joint_index;
std::size_t mimicked_joint_index;
double multiplier = 1.0;
double offset = 0.0;
};
std::vector<MimicJoint> mimic_joints_;
double parse_double(const std::string & text);
bool parse_bool(const std::string & text);
// Keep Track of Arm vs Drive Joints
struct JointGroupMember
{
std::size_t joint_index;
std::string joint_name;
bool percent = false;
double min = -1.0;
double max = 1.0;
};
std::vector<JointGroupMember> drive_joints_;
std::vector<JointGroupMember> arm_joints_;
// Joint name array will align with state and command interface array
// The command at index 3 of hw_command_ will be the joint name at index 3 of joint_names
std::vector<std::string> joint_names_;
std::vector<std::string> joint_types_;
// Pub Sub to real
std::string joint_state_topic_ = "real_joint_states";
std::string joint_command_topic_ = "real_joint_commands";
std::string joint_arm_command_topic_ = "real_arm_commands";
rclcpp::Node::SharedPtr node_;
std::shared_ptr<rclcpp::Publisher<sensor_msgs::msg::JointState>> real_publisher_ = nullptr;
std::shared_ptr<realtime_tools::RealtimePublisher<sensor_msgs::msg::JointState>>
realtime_real_publisher_ = nullptr;
std::shared_ptr<rclcpp::Publisher<sensor_msgs::msg::JointState>> real_arm_publisher_ = nullptr;
std::shared_ptr<realtime_tools::RealtimePublisher<sensor_msgs::msg::JointState>>
realtime_real_arm_publisher_ = nullptr;
bool subscriber_is_active_ = false;
rclcpp::Subscription<sensor_msgs::msg::JointState>::SharedPtr real_subscriber_ = nullptr;
realtime_tools::RealtimeBox<std::shared_ptr<sensor_msgs::msg::JointState>> received_joint_msg_ptr_{nullptr};
// Converts isaac position range -2pi - 2pi into expected ros position range -pi - pi
double convertToRosPosition(double real_position);
double convertToRosVelocity(double real_velocity);
// void convertToRealPositions(std::vector<double> ros_positions);
};
} // namespace swerve_hardware
#endif // SWERVE_HARDWARE__DIFFBOT_SYSTEM_HPP_ | 5,378 | C++ | 37.148936 | 110 | 0.748605 |
RoboEagles4828/offseason2023/src/swerve_hardware/include/swerve_hardware/motion_magic.hpp | #ifndef SWERVE_HARDWARE__MOTION_MAGIC_HPP_
#define SWERVE_HARDWARE__MOTION_MAGIC_HPP_
#include <memory>
#include <queue>
#include <string>
#include <utility>
#include <vector>
#include <cmath>
#include "swerve_hardware/visibility_control.h"
namespace swerve_hardware
{
class MotionMagic
{
public:
SWERVE_HARDWARE_PUBLIC
MotionMagic(double maxAcceleration, double maxVelocity);
SWERVE_HARDWARE_PUBLIC
double getNextVelocity(const double targetPosition, const double sensorPosition, const double sensorVelocity, const double dt);
SWERVE_HARDWARE_PUBLIC
double getPositionDifference(double targetPosition, double sensorPosition);
SWERVE_HARDWARE_PUBLIC
double getTotalTime(double targetPosition);
private:
double MAX_ACCELERATION;
double MAX_VELOCITY;
double MAX_JERK = 6 * M_PI;
double prevVel = 0.0;
double prevAcceleration = 0.0;
double prevError = 0.0;
double prevTargetPosition = 0.0;
double totalDistance = 0.0;
double zeroTime = 0.0;
double tolerance = 0.15;
double rampWindow1 = 0.3;
double rampWindow2 = 0.8;
double velocityInRampWindow1 = 0.1;
double velocityInRampWindow2 = 2.0;
double velocityInCruiseWindow = 3.0;
};
} // namespace swerve_hardware
#endif // SWERVE_HARDWARE__MOTION_MAGIC_HPP_
| 1,307 | C++ | 24.153846 | 131 | 0.729151 |
RoboEagles4828/offseason2023/src/swerve_hardware/include/swerve_hardware/isaac_drive.hpp | // Copyright 2021 ros2_control Development Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef SWERVE_HARDWARE__ISAAC_DRIVE_HPP_
#define SWERVE_HARDWARE__ISAAC_DRIVE_HPP_
#include <memory>
#include <string>
#include <vector>
#include <map>
#include "hardware_interface/handle.hpp"
#include "hardware_interface/hardware_info.hpp"
#include "hardware_interface/system_interface.hpp"
#include "hardware_interface/types/hardware_interface_return_values.hpp"
#include "rclcpp/clock.hpp"
#include "rclcpp/duration.hpp"
#include "rclcpp/macros.hpp"
#include "rclcpp/time.hpp"
#include "rclcpp_lifecycle/node_interfaces/lifecycle_node_interface.hpp"
#include "rclcpp_lifecycle/state.hpp"
#include "rclcpp/rclcpp.hpp"
#include "sensor_msgs/msg/joint_state.hpp"
#include "realtime_tools/realtime_box.h"
#include "realtime_tools/realtime_buffer.h"
#include "realtime_tools/realtime_publisher.h"
#include "swerve_hardware/visibility_control.h"
#include "swerve_hardware/motion_magic.hpp"
namespace swerve_hardware
{
class IsaacDriveHardware : public hardware_interface::SystemInterface
{
public:
RCLCPP_SHARED_PTR_DEFINITIONS(IsaacDriveHardware)
SWERVE_HARDWARE_PUBLIC
hardware_interface::CallbackReturn on_init(const hardware_interface::HardwareInfo & info) override;
SWERVE_HARDWARE_PUBLIC
std::vector<hardware_interface::StateInterface> export_state_interfaces() override;
SWERVE_HARDWARE_PUBLIC
std::vector<hardware_interface::CommandInterface> export_command_interfaces() override;
SWERVE_HARDWARE_PUBLIC
hardware_interface::CallbackReturn on_activate(const rclcpp_lifecycle::State & previous_state) override;
SWERVE_HARDWARE_PUBLIC
hardware_interface::CallbackReturn on_deactivate(const rclcpp_lifecycle::State & previous_state) override;
SWERVE_HARDWARE_PUBLIC
hardware_interface::return_type read(const rclcpp::Time & time, const rclcpp::Duration & period) override;
SWERVE_HARDWARE_PUBLIC
hardware_interface::return_type write(const rclcpp::Time & time, const rclcpp::Duration & period) override;
private:
// Store the command for the simulated robot
std::vector<double> hw_command_velocity_;
std::vector<double> hw_command_position_;
std::vector<double> hw_command_velocity_converted_;
// The state vectors
std::vector<double> hw_positions_;
std::vector<double> hw_velocities_;
// Joint name array will align with state and command interface array
// The command at index 3 of hw_command_ will be the joint name at index 3 of joint_names
std::vector<std::string> joint_names_;
std::vector<std::string> joint_types_;
double MAX_VELOCITY = 2 * M_PI;
double MAX_ACCELERATION = 4 * M_PI;
double previous_velocity = 0.0;
std::vector<MotionMagic> motion_magic_;
// Pub Sub to isaac
std::string joint_state_topic_ = "isaac_joint_states";
std::string joint_command_topic_ = "isaac_joint_commands";
rclcpp::Node::SharedPtr node_;
std::shared_ptr<rclcpp::Publisher<sensor_msgs::msg::JointState>> isaac_publisher_ = nullptr;
std::shared_ptr<realtime_tools::RealtimePublisher<sensor_msgs::msg::JointState>>
realtime_isaac_publisher_ = nullptr;
bool subscriber_is_active_ = false;
rclcpp::Subscription<sensor_msgs::msg::JointState>::SharedPtr isaac_subscriber_ = nullptr;
realtime_tools::RealtimeBox<std::shared_ptr<sensor_msgs::msg::JointState>> received_joint_msg_ptr_{nullptr};
std::vector<double> empty_;
// Converts isaac position range -2pi - 2pi into expected ros position range -pi - pi
double convertToRosPosition(double isaac_position);
double convertToRosVelocity(double isaac_velocity);
void convertToIsaacVelocities(std::vector<double> ros_velocities);
};
} // namespace swerve_hardware
#endif // SWERVE_HARDWARE__DIFFBOT_SYSTEM_HPP_ | 4,262 | C++ | 38.110091 | 110 | 0.762787 |
RoboEagles4828/offseason2023/src/teleop_twist_joy/src/teleop_twist_joy.cpp | /**
Software License Agreement (BSD)
\authors Mike Purvis <[email protected]>
\copyright Copyright (c) 2014, Clearpath Robotics, Inc., All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that
the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Clearpath Robotics nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WAR-
RANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, IN-
DIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cinttypes>
#include <functional>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <geometry_msgs/msg/twist.hpp>
#include <rclcpp/rclcpp.hpp>
#include <rclcpp_components/register_node_macro.hpp>
#include <rcutils/logging_macros.h>
#include <sensor_msgs/msg/joy.hpp>
#include "sensor_msgs/msg/imu.hpp"
#include "teleop_twist_joy/teleop_twist_joy.hpp"
#include "edna_interfaces/srv/set_bool.hpp"
#include <functional> // for bind()
using namespace std;
#define ROS_INFO_NAMED RCUTILS_LOG_INFO_NAMED
#define ROS_INFO_COND_NAMED RCUTILS_LOG_INFO_EXPRESSION_NAMED
namespace teleop_twist_joy
{
/**
* Internal members of class. This is the pimpl idiom, and allows more flexibility in adding
* parameters later without breaking ABI compatibility, for robots which link TeleopTwistJoy
* directly into base nodes.
*/
struct TeleopTwistJoy::Impl
{
void joyCallback(const sensor_msgs::msg::Joy::SharedPtr joy);
void sendCmdVelMsg(const sensor_msgs::msg::Joy::SharedPtr &, const std::string &which_map);
void imuCallback(const sensor_msgs::msg::Imu::SharedPtr imu_msg);
void timerCallback();
void resetOrientationCallback(const std::shared_ptr<edna_interfaces::srv::SetBool::Request> request, std::shared_ptr<edna_interfaces::srv::SetBool::Response> response);
rclcpp::Subscription<sensor_msgs::msg::Joy>::SharedPtr joy_sub;
rclcpp::Subscription<sensor_msgs::msg::Imu>::SharedPtr imu_sub;
rclcpp::Publisher<geometry_msgs::msg::Twist>::SharedPtr cmd_vel_pub;
rclcpp::Service<edna_interfaces::srv::SetBool>::SharedPtr reset_orientation_service;
rclcpp::TimerBase::SharedPtr timer_callback_;
rclcpp::Client<edna_interfaces::srv::SetBool>::SharedPtr start_writer_client_;
sensor_msgs::msg::Imu::SharedPtr last_msg;
bool require_enable_button;
int64_t enable_button;
int64_t enable_turbo_button;
int64_t enable_field_oriented_button;
int64_t start_writer_button;
int fieldOrientationButtonLastState = 0;
int turboButtonLastState = 0;
double last_offset = 0.0;
double rotation_offset = 0.0;
bool fieldOrientationEnabled = true;
bool turboEnabled = false;
int serviceButtonLastState = 0;
bool serviceEnabled = false;
std::map<std::string, int64_t> axis_linear_map;
std::map<std::string, std::map<std::string, double>> scale_linear_map;
std::map<std::string, int64_t> axis_angular_map;
std::map<std::string, std::map<std::string, double>> scale_angular_map;
bool sent_disable_msg;
};
/**
* Constructs TeleopTwistJoy.
*/
TeleopTwistJoy::TeleopTwistJoy(const rclcpp::NodeOptions &options) : Node("teleop_twist_joy_node", options)
{
pimpl_ = new Impl;
// rclcpp::Node node = Node("teleop_twist_joy_node", options); sensor_msgs/msg/Imu
pimpl_->cmd_vel_pub = this->create_publisher<geometry_msgs::msg::Twist>("cmd_vel", 10);
pimpl_->imu_sub = this->create_subscription<sensor_msgs::msg::Imu>("zed/imu/data", rclcpp::QoS(10).best_effort(),
std::bind(&TeleopTwistJoy::Impl::imuCallback, this->pimpl_, std::placeholders::_1));
pimpl_->joy_sub = this->create_subscription<sensor_msgs::msg::Joy>("joy", rclcpp::QoS(10).best_effort(),
std::bind(&TeleopTwistJoy::Impl::joyCallback, this->pimpl_, std::placeholders::_1));
// pimpl_->client = this->create_client<writer_srv::srv::StartWriter>("start_writer");
// pimpl_->timer_callback_ = this->create_wall_timer(std::chrono::duration<double>(0.1), std::bind(&TeleopTwistJoy::Impl::timerCallback,this->pimpl_));
// pimpl_->client = create_client<writer_srv::srv::StartWriter>("start_writer",
// [this](std::shared_ptr<writer_srv::srv::StartWriter::Request> /*request*/, // NOLINT
// std::shared_ptr<writer_srv::srv::StartWriter::Response> response) { // NOLINT
// return startServiceCallback(std::move(response)); // NOLINT
pimpl_->reset_orientation_service = create_service<edna_interfaces::srv::SetBool>("reset_field_oriented", std::bind(&TeleopTwistJoy::Impl::resetOrientationCallback, this->pimpl_, std::placeholders::_1, std::placeholders::_2));
// });
pimpl_->start_writer_client_ = create_client<edna_interfaces::srv::SetBool>("set_bool");
pimpl_->require_enable_button = this->declare_parameter("require_enable_button", true);
pimpl_->enable_button = this->declare_parameter("enable_button", 5);
pimpl_->enable_turbo_button = this->declare_parameter("enable_turbo_button", -1);
pimpl_->enable_field_oriented_button = this->declare_parameter("enable_field_oriented_button", 8);
pimpl_->start_writer_button = this->declare_parameter("start_writer_button", 6);
this->declare_parameter("offset", 0.0);
pimpl_->last_offset = this->get_parameter("offset").as_double();
std::map<std::string, int64_t> default_linear_map{
{"x", 5L},
{"y", -1L},
{"z", -1L},
};
this->declare_parameters("axis_linear", default_linear_map);
this->get_parameters("axis_linear", pimpl_->axis_linear_map);
std::map<std::string, int64_t> default_angular_map{
{"yaw", 2L},
{"pitch", -1L},
{"roll", -1L},
};
this->declare_parameters("axis_angular", default_angular_map);
this->get_parameters("axis_angular", pimpl_->axis_angular_map);
std::map<std::string, double> default_scale_linear_normal_map{
{"x", 0.5},
{"y", 0.0},
{"z", 0.0},
};
this->declare_parameters("scale_linear", default_scale_linear_normal_map);
this->get_parameters("scale_linear", pimpl_->scale_linear_map["normal"]);
std::map<std::string, double> default_scale_linear_turbo_map{
{"x", 1.0},
{"y", 0.0},
{"z", 0.0},
};
this->declare_parameters("scale_linear_turbo", default_scale_linear_turbo_map);
this->get_parameters("scale_linear_turbo", pimpl_->scale_linear_map["turbo"]);
std::map<std::string, double> default_scale_angular_normal_map{
{"yaw", 0.5},
{"pitch", 0.0},
{"roll", 0.0},
};
this->declare_parameters("scale_angular", default_scale_angular_normal_map);
this->get_parameters("scale_angular", pimpl_->scale_angular_map["normal"]);
std::map<std::string, double> default_scale_angular_turbo_map{
{"yaw", 1.0},
{"pitch", 0.0},
{"roll", 0.0},
};
this->declare_parameters("scale_angular_turbo", default_scale_angular_turbo_map);
this->get_parameters("scale_angular_turbo", pimpl_->scale_angular_map["turbo"]);
ROS_INFO_COND_NAMED(pimpl_->require_enable_button, "TeleopTwistJoy",
"Teleop enable button %" PRId64 ".", pimpl_->enable_button);
ROS_INFO_COND_NAMED(pimpl_->enable_turbo_button >= 0, "TeleopTwistJoy",
"Turbo on button %" PRId64 ".", pimpl_->enable_turbo_button);
for (std::map<std::string, int64_t>::iterator it = pimpl_->axis_linear_map.begin();
it != pimpl_->axis_linear_map.end(); ++it)
{
ROS_INFO_COND_NAMED(it->second != -1L, "TeleopTwistJoy", "Linear axis %s on %" PRId64 " at scale %f.",
it->first.c_str(), it->second, pimpl_->scale_linear_map["normal"][it->first]);
ROS_INFO_COND_NAMED(pimpl_->enable_turbo_button >= 0 && it->second != -1, "TeleopTwistJoy",
"Turbo for linear axis %s is scale %f.", it->first.c_str(), pimpl_->scale_linear_map["turbo"][it->first]);
}
for (std::map<std::string, int64_t>::iterator it = pimpl_->axis_angular_map.begin();
it != pimpl_->axis_angular_map.end(); ++it)
{
ROS_INFO_COND_NAMED(it->second != -1L, "TeleopTwistJoy", "Angular axis %s on %" PRId64 " at scale %f.",
it->first.c_str(), it->second, pimpl_->scale_angular_map["normal"][it->first]);
ROS_INFO_COND_NAMED(pimpl_->enable_turbo_button >= 0 && it->second != -1, "TeleopTwistJoy",
"Turbo for angular axis %s is scale %f.", it->first.c_str(), pimpl_->scale_angular_map["turbo"][it->first]);
}
pimpl_->sent_disable_msg = false;
auto param_callback =
[this](std::vector<rclcpp::Parameter> parameters)
{
static std::set<std::string> intparams = {"axis_linear.x", "axis_linear.y", "axis_linear.z",
"axis_angular.yaw", "axis_angular.pitch", "axis_angular.roll",
"enable_button", "enable_turbo_button", "enable_field_oriented_button", "start_writer_button", "offset"};
static std::set<std::string> doubleparams = {"scale_linear.x", "scale_linear.y", "scale_linear.z",
"scale_linear_turbo.x", "scale_linear_turbo.y", "scale_linear_turbo.z",
"scale_angular.yaw", "scale_angular.pitch", "scale_angular.roll",
"scale_angular_turbo.yaw", "scale_angular_turbo.pitch", "scale_angular_turbo.roll"};
static std::set<std::string> boolparams = {"require_enable_button"};
auto result = rcl_interfaces::msg::SetParametersResult();
result.successful = true;
// Loop to check if changed parameters are of expected data type
for (const auto ¶meter : 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 ¶meter : parameters)
{
if (parameter.get_name() == "require_enable_button")
{
this->pimpl_->require_enable_button = parameter.get_value<rclcpp::PARAMETER_BOOL>();
}
if (parameter.get_name() == "enable_button")
{
this->pimpl_->enable_button = parameter.get_value<rclcpp::PARAMETER_INTEGER>();
}
else if (parameter.get_name() == "enable_turbo_button")
{
this->pimpl_->enable_turbo_button = parameter.get_value<rclcpp::PARAMETER_INTEGER>();
}
else if (parameter.get_name() == "enable_field_oriented_button")
{
this->pimpl_->enable_field_oriented_button = parameter.get_value<rclcpp::PARAMETER_INTEGER>();
}
else if (parameter.get_name() == "start_writer_button")
{
this->pimpl_->start_writer_button = parameter.get_value<rclcpp::PARAMETER_INTEGER>();
}
else if (parameter.get_name() == "axis_linear.x")
{
this->pimpl_->axis_linear_map["x"] = parameter.get_value<rclcpp::PARAMETER_INTEGER>();
}
else if (parameter.get_name() == "axis_linear.y")
{
this->pimpl_->axis_linear_map["y"] = parameter.get_value<rclcpp::PARAMETER_INTEGER>();
}
else if (parameter.get_name() == "axis_linear.z")
{
this->pimpl_->axis_linear_map["z"] = parameter.get_value<rclcpp::PARAMETER_INTEGER>();
}
else if (parameter.get_name() == "axis_angular.yaw")
{
this->pimpl_->axis_angular_map["yaw"] = parameter.get_value<rclcpp::PARAMETER_INTEGER>();
}
else if (parameter.get_name() == "axis_angular.pitch")
{
this->pimpl_->axis_angular_map["pitch"] = parameter.get_value<rclcpp::PARAMETER_INTEGER>();
}
else if (parameter.get_name() == "axis_angular.roll")
{
this->pimpl_->axis_angular_map["roll"] = parameter.get_value<rclcpp::PARAMETER_INTEGER>();
}
else if (parameter.get_name() == "scale_linear_turbo.x")
{
this->pimpl_->scale_linear_map["turbo"]["x"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>();
}
else if (parameter.get_name() == "scale_linear_turbo.y")
{
this->pimpl_->scale_linear_map["turbo"]["y"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>();
}
else if (parameter.get_name() == "scale_linear_turbo.z")
{
this->pimpl_->scale_linear_map["turbo"]["z"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>();
}
else if (parameter.get_name() == "scale_linear.x")
{
this->pimpl_->scale_linear_map["normal"]["x"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>();
}
else if (parameter.get_name() == "scale_linear.y")
{
this->pimpl_->scale_linear_map["normal"]["y"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>();
}
else if (parameter.get_name() == "scale_linear.z")
{
this->pimpl_->scale_linear_map["normal"]["z"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>();
}
else if (parameter.get_name() == "scale_angular_turbo.yaw")
{
this->pimpl_->scale_angular_map["turbo"]["yaw"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>();
}
else if (parameter.get_name() == "scale_angular_turbo.pitch")
{
this->pimpl_->scale_angular_map["turbo"]["pitch"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>();
}
else if (parameter.get_name() == "scale_angular_turbo.roll")
{
this->pimpl_->scale_angular_map["turbo"]["roll"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>();
}
else if (parameter.get_name() == "scale_angular.yaw")
{
this->pimpl_->scale_angular_map["normal"]["yaw"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>();
}
else if (parameter.get_name() == "scale_angular.pitch")
{
this->pimpl_->scale_angular_map["normal"]["pitch"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>();
}
else if (parameter.get_name() == "scale_angular.roll")
{
this->pimpl_->scale_angular_map["normal"]["roll"] = parameter.get_value<rclcpp::PARAMETER_DOUBLE>();
}
}
return result;
};
callback_handle = this->add_on_set_parameters_callback(param_callback);
}
TeleopTwistJoy::~TeleopTwistJoy()
{
delete pimpl_;
}
double getVal(sensor_msgs::msg::Joy::SharedPtr joy_msg, const std::map<std::string, int64_t> &axis_map,
const std::map<std::string, double> &scale_map, const std::string &fieldname)
{
if (axis_map.find(fieldname) == axis_map.end() ||
axis_map.at(fieldname) == -1L ||
scale_map.find(fieldname) == scale_map.end() ||
static_cast<int>(joy_msg->axes.size()) <= axis_map.at(fieldname))
{
return 0.0;
}
return joy_msg->axes[axis_map.at(fieldname)] * scale_map.at(fieldname);
}
double get_scale_val(const std::map<std::string, int64_t> &axis_map,
const std::map<std::string, double> &scale_map, const std::string &fieldname)
{
if (axis_map.find(fieldname) == axis_map.end() ||
axis_map.at(fieldname) == -1L ||
scale_map.find(fieldname) == scale_map.end())
{
return 0.0;
}
return scale_map.at(fieldname);
}
double get_orientation_val(sensor_msgs::msg::Imu::SharedPtr imu_msg)
{
if (!imu_msg)
{
return 0.0;
}
double x = imu_msg->orientation.x;
double y = imu_msg->orientation.y;
double z = imu_msg->orientation.z;
double w = imu_msg->orientation.w;
double siny_cosp = 2 * (w * z + x * y);
double cosy_cosp = 1 - 2 * (y * y + z * z);
double angle = std::atan2(siny_cosp, cosy_cosp);
return angle;
}
double correct_joystick_pos(const std::map<std::string, double> &scale_map, const std::string &fieldname, double lin_x_vel, double lin_y_vel)
{
if (sqrt(pow(lin_x_vel, 2) + pow(lin_y_vel, 2)) > 1)
{
double scale = scale_map.at(fieldname);
if (scale < 0.001)
{
scale *= 10000;
}
if (fieldname == "x")
{
double vel_to_correct = sin(atan2(lin_x_vel, lin_y_vel)) * scale;
return vel_to_correct;
}
else if (fieldname == "y")
{
double vel_to_correct = cos(atan2(lin_x_vel, lin_y_vel)) * scale;
return vel_to_correct;
}
}
else
{
if (fieldname == "x")
{
double vel_to_correct = sin(atan2(lin_x_vel, lin_y_vel)) * sqrt(pow(lin_x_vel, 2) + pow(lin_y_vel, 2));
return vel_to_correct;
}
else if (fieldname == "y")
{
double vel_to_correct = cos(atan2(lin_x_vel, lin_y_vel)) * sqrt(pow(lin_x_vel, 2) + pow(lin_y_vel, 2));
return vel_to_correct;
}
}
return 0.0;
}
// void TeleopTwistJoy::startServiceCallBack(const std::shared_ptr<edna_interfaces::srv::SetBool::Response> response)
// {
// if(joy){
// }
// }
void TeleopTwistJoy::Impl::timerCallback()
{
// it's good to firstly check if the service server is even ready to be called
if (start_writer_client_->service_is_ready() && serviceEnabled && serviceButtonLastState == 1)
{
auto request = std::make_shared<edna_interfaces::srv::SetBool::Request>();
request->data = true;
while (!start_writer_client_->wait_for_service(1s))
{
if (!rclcpp::ok())
{
RCLCPP_ERROR(rclcpp::get_logger("teleop_twist_joy"), "Interrupted while waiting for the service. Exiting.");
break;
}
RCLCPP_INFO(rclcpp::get_logger("teleop_twist_joy"), "service not available, waiting again...");
}
auto result = start_writer_client_->async_send_request(request);
}
else if (start_writer_client_->service_is_ready() && !serviceEnabled && serviceButtonLastState == 1)
{
auto request = std::make_shared<edna_interfaces::srv::SetBool::Request>();
request->data = false;
while (!start_writer_client_->wait_for_service(1s))
{
if (!rclcpp::ok())
{
RCLCPP_ERROR(rclcpp::get_logger("teleop_twist_joy"), "Interrupted while waiting for the service. Exiting.");
break;
}
RCLCPP_INFO(rclcpp::get_logger("teleop_twist_joy"), "service not available, waiting again...");
}
auto result = start_writer_client_->async_send_request(request);
// RCLCPP_INFO(rclcpp::get_logger("teleop_twist_joy"), "Bag recording stopped: %d", !result.get()->recording);
// RCLCPP_INFO(rclcpp::get_logger("teleop_twist_joy"), "Path of Bag: %s", result.get()->path.c_str());
}
else if (!start_writer_client_->service_is_ready())
RCLCPP_WARN(rclcpp::get_logger("teleop_twist_joy"), "[ServiceClientExample]: not calling service using callback, service not ready!");
}
void TeleopTwistJoy::Impl::resetOrientationCallback(const std::shared_ptr<edna_interfaces::srv::SetBool::Request> request, std::shared_ptr<edna_interfaces::srv::SetBool::Response> response)
{
RCLCPP_INFO(rclcpp::get_logger("TeleopTwistJoy"), "received service call: %d", request->data);
if (request->data)
{
rotation_offset=3.1415;
}
response->message = "succeeded";
response->success = true;
}
void TeleopTwistJoy::Impl::sendCmdVelMsg(const sensor_msgs::msg::Joy::SharedPtr &joy_msg,
const std::string &which_map)
{
// Initializes with zeros by default.
auto cmd_vel_msg = std::make_unique<geometry_msgs::msg::Twist>();
double lin_x_vel = getVal(joy_msg, axis_linear_map, scale_linear_map[which_map], "x");
double lin_y_vel = getVal(joy_msg, axis_linear_map, scale_linear_map[which_map], "y");
double ang_z_vel = getVal(joy_msg, axis_angular_map, scale_angular_map[which_map], "yaw");
double temp = correct_joystick_pos(scale_linear_map[which_map], "x", lin_x_vel, lin_y_vel);
lin_y_vel = correct_joystick_pos(scale_linear_map[which_map], "y", lin_x_vel, lin_y_vel);
lin_x_vel = temp;
// RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "%f",lin_x_vel);
// for( uint i =0u; i<joy_msg->buttons.size(); i++){
// RCLCPP_INFO(rclcpp::get_logger("IsaacDriveHardware"), "%d:%d:%ld",joy_msg->buttons[i],i,enable_field_oriented_button);
// }
if (enable_field_oriented_button >= 0 && static_cast<int>(joy_msg->buttons.size()) > enable_field_oriented_button)
{
auto state = joy_msg->buttons[enable_field_oriented_button];
if (state == 1 && fieldOrientationButtonLastState == 0)
{
fieldOrientationEnabled = !fieldOrientationEnabled;
RCLCPP_INFO(rclcpp::get_logger("TeleopTwistJoy"), "Field Oriented: %d", fieldOrientationEnabled);
}
fieldOrientationButtonLastState = state;
}
if (start_writer_button >= 0 && static_cast<int>(joy_msg->buttons.size()) > start_writer_button)
{
auto state = joy_msg->buttons[start_writer_button];
if (state == 1 && serviceButtonLastState == 0)
{
serviceEnabled = !serviceEnabled;
RCLCPP_INFO(rclcpp::get_logger("TeleopTwistJoy"), "Writer State: %d", serviceEnabled);
}
serviceButtonLastState = state;
}
// RCLCPP_INFO(rclcpp::get_logger("TeleopTwistJoy"), "robot_orientation: %f",last_offset);
// Math for field oriented drive
if (fieldOrientationEnabled)
{
double robot_imu_orientation = (get_orientation_val(last_msg));
robot_imu_orientation += (ang_z_vel * last_offset) + rotation_offset;
// RCLCPP_INFO(rclcpp::get_logger("TeleopTwistJoy"), "robot_orientation: %f", robot_imu_orientation);
double temp = lin_x_vel * cos(robot_imu_orientation) + lin_y_vel * sin(robot_imu_orientation);
lin_y_vel = -1 * lin_x_vel * sin(robot_imu_orientation) + lin_y_vel * cos(robot_imu_orientation);
lin_x_vel = temp;
}
// Set Velocities in twist msg and publish
cmd_vel_msg->linear.x = lin_x_vel;
cmd_vel_msg->linear.y = lin_y_vel;
cmd_vel_msg->linear.z = getVal(joy_msg, axis_linear_map, scale_linear_map[which_map], "z");
cmd_vel_msg->angular.z = getVal(joy_msg, axis_angular_map, scale_angular_map[which_map], "yaw");
cmd_vel_msg->angular.y = getVal(joy_msg, axis_angular_map, scale_angular_map[which_map], "pitch");
cmd_vel_msg->angular.x = getVal(joy_msg, axis_angular_map, scale_angular_map[which_map], "roll");
cmd_vel_pub->publish(std::move(cmd_vel_msg));
sent_disable_msg = false;
}
void TeleopTwistJoy::Impl::joyCallback(const sensor_msgs::msg::Joy::SharedPtr joy_msg)
{
if (enable_turbo_button >= 0 && static_cast<int>(joy_msg->buttons.size()) > enable_turbo_button)
{
auto state = joy_msg->buttons[enable_turbo_button];
if (state == 1 && turboButtonLastState == 0)
{
turboEnabled = !turboEnabled;
RCLCPP_INFO(rclcpp::get_logger("TeleopTwistJoy"), "Turbo: %d", turboEnabled);
}
turboButtonLastState = state;
}
if (turboEnabled)
{
sendCmdVelMsg(joy_msg, "turbo");
}
else if (!require_enable_button ||
(static_cast<int>(joy_msg->buttons.size()) > enable_button &&
joy_msg->buttons[enable_button]))
{
sendCmdVelMsg(joy_msg, "normal");
}
else
{
// When enable button is released, immediately send a single no-motion command
// in order to stop the robot.
if (!sent_disable_msg)
{
// Initializes with zeros by default.
auto cmd_vel_msg = std::make_unique<geometry_msgs::msg::Twist>();
cmd_vel_pub->publish(std::move(cmd_vel_msg));
sent_disable_msg = true;
}
}
}
void TeleopTwistJoy::Impl::imuCallback(const sensor_msgs::msg::Imu::SharedPtr imu_msg)
{
// Saves current message as global pointer
last_msg = imu_msg;
}
} // namespace teleop_twist_joy
RCLCPP_COMPONENTS_REGISTER_NODE(teleop_twist_joy::TeleopTwistJoy)
| 26,597 | C++ | 43.404007 | 230 | 0.615859 |
RoboEagles4828/offseason2023/src/teleop_twist_joy/src/teleop_node.cpp | /**
Software License Agreement (BSD)
\file teleop_node.cpp
\authors Mike Purvis <[email protected]>
\copyright Copyright (c) 2014, Clearpath Robotics, Inc., All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that
the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Clearpath Robotics nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WAR-
RANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, IN-
DIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <memory>
#include <rclcpp/rclcpp.hpp>
#include "teleop_twist_joy/teleop_twist_joy.hpp"
int main(int argc, char *argv[])
{
rclcpp::init(argc, argv);
rclcpp::spin(std::make_unique<teleop_twist_joy::TeleopTwistJoy>(rclcpp::NodeOptions()));
rclcpp::shutdown();
return 0;
}
| 1,931 | C++ | 44.999999 | 110 | 0.785085 |
RoboEagles4828/offseason2023/src/teleop_twist_joy/include/teleop_twist_joy/teleop_twist_joy.hpp | /**
Software License Agreement (BSD)
\authors Mike Purvis <[email protected]>
\copyright Copyright (c) 2014, Clearpath Robotics, Inc., All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that
the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Clearpath Robotics nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WAR-
RANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, IN-
DIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TELEOP_TWIST_JOY_TELEOP_TWIST_JOY_H
#define TELEOP_TWIST_JOY_TELEOP_TWIST_JOY_H
#include <rclcpp/rclcpp.hpp>
#include "teleop_twist_joy/teleop_twist_joy_export.h"
namespace teleop_twist_joy
{
/**
* Class implementing a basic Joy -> Twist translation.
*/
class TELEOP_TWIST_JOY_EXPORT TeleopTwistJoy : public rclcpp::Node
{
public:
explicit TeleopTwistJoy(const rclcpp::NodeOptions& options);
virtual ~TeleopTwistJoy();
private:
struct Impl;
Impl* pimpl_;
OnSetParametersCallbackHandle::SharedPtr callback_handle;
};
} // namespace teleop_twist_joy
#endif // TELEOP_TWIST_JOY_TELEOP_TWIST_JOY_H
| 2,237 | C++ | 41.226414 | 110 | 0.788556 |
RoboEagles4828/offseason2023/src/frc_auton/frc_auton/test_frc_stage.py | import rclpy
from rclpy.node import Node
from std_msgs.msg import Bool, String
class StagePublisher(Node):
def __init__(self):
super().__init__('stage_publisher')
self.publisher_ = self.create_publisher(String, '/real/frc_stage', 10)
timer_period = 0.5 # seconds
self.timer = self.create_timer(timer_period, self.timer_callback)
self.i = 0
def timer_callback(self):
msg = String()
msg.data = "AUTON|False|False"
self.publisher_.publish(msg)
self.get_logger().info('Publishing: %s' % msg.data)
self.i += 1
def main(args=None):
rclpy.init(args=args)
minimal_publisher = StagePublisher()
rclpy.spin(minimal_publisher)
# Destroy the node explicitly
# (optional - otherwise it will be done automatically
# when the garbage collector destroys the node object)
minimal_publisher.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main() | 974 | Python | 23.999999 | 78 | 0.63347 |
RoboEagles4828/offseason2023/src/frc_auton/frc_auton/writer.py | from std_msgs.msg import String
from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint
from geometry_msgs.msg import Twist
import rclpy
from rclpy.node import Node
import os
import rclpy
from rclpy.node import Node
from rclpy.serialization import serialize_message
from std_msgs.msg import String
from edna_interfaces.srv import SetBool
import rosbag2_py
# create writer instance and open for writing
class StartWriting(Node):
def __init__(self):
super().__init__('start_writer')
self.subscription_stage =self.create_subscription(String, 'frc_stage', self.stage_callback, 10)
self.srv = self.create_service(SetBool, 'set_bool', self.service_callback)
self.stage = ""
self.fms = "False"
self.is_disabled = "True"
self.service_enabled = False
def service_callback(self, request, response):
self.bag_writer = BagWriter()
self.service_enabled = request.data
if(self.service_enabled):
self.start_bag_writer()
self.get_logger().info(f'Service Enabled: {self.service_enabled}')
response.sucess = True
response.message = self.bag_writer.path
return response
def start_bag_writer(self):
if (self.stage.lower() == "teleop" or self.stage.lower() == "auton") and (self.fms=='True' or self.service_enabled) and self.is_disabled=='False':
rclpy.spin(self.bag_writer)
self.bag_writer.destroy_node()
rclpy.shutdown()
def stage_callback(self, msg):
data = str(msg.data).split('|')
self.stage = (data[0])
self.fms = str(data[1])
self.is_disabled = str(data[2])
class BagWriter(Node):
def __init__(self):
super().__init__('bag_writer')
self.curr_file_path = os.path.abspath(__file__)
self.project_root_path = os.path.abspath(os.path.join(self.curr_file_path, "../../../.."))
self.package_root = os.path.join(self.project_root_path, 'src/frc_auton')
self.subscription_arm = self.create_subscription(JointTrajectory,'joint_trajectory_controller/joint_trajectory',self.arm_callback,10)
self.subscription_swerve = self.create_subscription(Twist,'swerve_controller/cmd_vel_unstamped',self.swerve_callback,10)
file_counter= int(len(os.listdir(f'{self.package_root}/frc_auton/Auto_ros_bag')))
self.path = f'{self.package_root}/frc_auton/Auto_ros_bag/bag_'+str(file_counter)
self.writer = rosbag2_py.SequentialWriter()
storage_options = rosbag2_py._storage.StorageOptions(uri=self.path,storage_id='sqlite3')
converter_options = rosbag2_py._storage.ConverterOptions('', '')
self.writer.open(storage_options, converter_options)
topic_info_arm = rosbag2_py._storage.TopicMetadata(name=self.subscription_arm.topic_name,type='trajectory_msgs/msg/JointTrajectory',serialization_format='cdr')
self.writer.create_topic(topic_info_arm)
topic_info_swerve = rosbag2_py._storage.TopicMetadata(name=self.subscription_swerve.topic_name,type='geometry_msgs/msg/Twist',serialization_format='cdr')
self.writer.create_topic(topic_info_swerve)
def swerve_callback(self, msg):
self.writer.write(
self.subscription_swerve.topic_name,
serialize_message(msg),
self.get_clock().now().nanoseconds)
def arm_callback(self, msg):
self.writer.write(
self.subscription_arm.topic_name,
serialize_message(msg),
self.get_clock().now().nanoseconds)
def main(args=None):
rclpy.init(args=args)
service_writer = StartWriting()
rclpy.spin(service_writer)
service_writer.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main() | 3,865 | Python | 39.694736 | 167 | 0.649677 |
RoboEagles4828/offseason2023/src/frc_auton/frc_auton/policy_runner.py | import rclpy
from rclpy.node import Node
from std_msgs.msg import Float32
from nav_msgs.msg import Odometry
from sensor_msgs.msg import JointState
from geometry_msgs.msg import Twist
import numpy as np
import torch
from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint
class Reader(Node):
def __init__(self):
super().__init__("reinforcement_learning_runner")
# self.robot_ip = robot_ip
self.policy = torch.load("/workspaces/edna2023/isaac/Swervesim/swervesim/runs/SwerveCS/nn/SwerveCS.pth")
self.joint_action_pub = self.create_publisher(Twist, "cmd_vel", 10)
self.joint_trajectory_action_pub = self.create_publisher(Twist, "joint_trajectory_message", 10)
self.odom_sub = self.create_subscription(Float32, "odom", self.odom_callback, 10)
self.joint_state_sub = self.create_subscription(Float32, "joint_state", self.joint_state_callback, 10)
self.odom_msg = Odometry()
self.joint_state_msg = JointState()
self.twist_msg = Twist()
self.cmds = JointTrajectory()
self.position_cmds = JointTrajectoryPoint()
self.episode_reward = 0
self.step = 0
self.joints = [
'arm_roller_bar_joint',
'elevator_center_joint',
'elevator_outer_1_joint',
'elevator_outer_2_joint',
'top_gripper_right_arm_joint',
'top_gripper_left_arm_joint',
'top_slider_joint',
'bottom_intake_joint',
]
def get_action(self, msg):
obs = np.array([msg.data], dtype=np.float32)
action = self.policy(torch.tensor(obs).float())
self.twist_msg.linear.x = action[0].detach().numpy()
self.twist_msg.linear.y = action[1].detach().numpy()
self.twist_msg.angular.z = action[2].detach().numpy()
self.position_cmds.positions = [
action[3].detach().numpy(),
action[4].detach().numpy(),
action[5].detach().numpy(),
action[4].detach().numpy(),
action[6].detach().numpy(),
action[6].detach().numpy(),
action[7].detach().numpy(),
action[6].detach().numpy(),
action[8].detach().numpy(),
action[8].detach().numpy(),
]
self.cmds.joint_names = self.joints
self.cmds.points = [self.position_cmds]
self.publisher_.publish(self.cmds)
self.action_pub.publish(self.twist_msg)
self.step += 1
def joint_state_callback(self, msg):
if(msg != None):
self.joint_state_msg = msg
return
def odom_callback(self, msg):
if(msg != None):
self.odom_msg = msg
return
def get_reward():
return
def main(args=None):
# env = gym.create_env("RealRobot", ip=self.robot_ip)
rclpy.init(args=args)
reader = Reader()
rclpy.spin(reader)
# env.disconnect()
if __name__ == '__main__':
main() | 2,977 | Python | 35.765432 | 112 | 0.593215 |
RoboEagles4828/offseason2023/src/frc_auton/frc_auton/reader.py | import rclpy
from rclpy.node import Node
from geometry_msgs.msg import Twist
from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint
from std_msgs.msg import String
import rosbag2_py
from pathlib import Path
from rclpy.serialization import deserialize_message
import rosbag2_py
from std_msgs.msg import String
import os
from time import time
import yaml
import math
from edna_interfaces.srv import SetBool
class MinimalClientAsync(Node):
def __init__(self):
super().__init__('minimal_client_async')
self.client = self.create_client(SetBool, 'reset_field_oriented')
while not self.client.wait_for_service(timeout_sec=1.0):
self.get_logger().info('service not available, waiting again...')
self.request = SetBool.Request()
def send_request(self, request):
self.request.data = request
self.future = self.client.call_async(self.request)
rclpy.spin_until_future_complete(self, self.future)
return self.future.result()
class StageSubscriber(Node):
def __init__(self):
super().__init__('stage_subscriber')
self.curr_file_path = os.path.abspath(__file__)
self.project_root_path = os.path.abspath(os.path.join(self.curr_file_path, "../../../.."))
self.package_root = os.path.join(self.project_root_path, 'src/frc_auton')
# minimal_client = MinimalClientAsync()
# response = minimal_client.send_request(True)
# minimal_client.get_logger().info(
# 'Result of add_two_ints: for %d + %d = %s' %
# (True, response.success, response.message))
# rclpy.spin_once(minimal_client)
# minimal_client.destroy_node()
file_counter= int(len(os.listdir(f'{self.package_root}/frc_auton/Auto_ros_bag')))-1
# self.reader = rosbag2_py.SequentialReader()
# self.converter_options = rosbag2_py.ConverterOptions(input_serialization_format='cdr',output_serialization_format='cdr')
# self.reader.open(self.storage_options,self.converter_options)
if file_counter != -1:
self.subscription = self.create_subscription(String,'frc_stage',self.listener_callback,10)
self.publish_twist = self.create_publisher(Twist,'swerve_controller/cmd_vel_unstamped',10)
self.publish_trajectory = self.create_publisher(JointTrajectory,'joint_trajectory_controller/joint_trajectory',10)
self.changed_stage = False
self.stage= ""
self.fms = "False"
self.isdisabled = "True"
self.doAuton = False
self.cmd = Twist()
self.cmd.linear.x = 0.0
self.cmd.linear.y = 0.0
self.cmd.angular.z = 0.0
self.timeInSeconds = 2.0
self.taxiTimeDuration = 2.0
# joint trajectory msg stuff
self.joints = [
'arm_roller_bar_joint',
'elevator_center_joint',
'elevator_outer_1_joint',
'elevator_outer_2_joint',
'top_gripper_right_arm_joint',
'top_gripper_left_arm_joint',
'top_slider_joint',
'bottom_intake_joint',
]
self.cmds: JointTrajectory = JointTrajectory()
self.cmds.joint_names = self.joints
self.position_cmds = JointTrajectoryPoint()
self.cmds.points = [self.position_cmds]
self.cmds.points[0].positions = [0.0] * len(self.joints)
# yaml
self.curr_file_path = os.path.abspath(__file__)
self.project_root_path = os.path.abspath(os.path.join(self.curr_file_path, "../../../.."))
self.yaml_path = os.path.join(self.project_root_path, 'src/edna_bringup/config/teleop-control.yaml')
with open(self.yaml_path, 'r') as f:
self.yaml = yaml.safe_load(f)
self.joint_map = self.yaml['joint_mapping']
self.joint_limits = self.yaml["joint_limits"]
# task times
self.tasks = [
{ 'dur': 0.25, 'task': self.gripperManager, 'arg': 0 },
{ 'dur': 0.5, 'task': self.armHeightManager, 'arg': 1 },
{ 'dur': 3.5, 'task': self.armExtensionManager, 'arg': 1 },
{ 'dur': 0.5, 'task': self.gripperManager, 'arg': 1 },
{ 'dur': 2.5, 'task': self.armExtensionManager, 'arg': 0 },
{ 'dur': 0.5, 'task': self.armHeightManager, 'arg': 0 },
{ 'dur': 3.0, 'task': self.goBackwards, 'arg': -1.5 },
{ 'dur': 0.1, 'task': self.stop, 'arg': 0 },
{ 'dur': 2.1, 'task': self.turnAround, 'arg': math.pi / 2 },
{ 'dur': 0.1, 'task': self.stop, 'arg': 0 },
]
self.conePlacementDuration = 0
for task in self.tasks:
self.conePlacementDuration += task['dur']
# TURN AROUND STUFF
self.turnCmd = Twist()
self.turnCmd.linear.x = 0.0
self.turnCmd.linear.y = 0.0
self.turnCmd.angular.z = 0.0
self.turnTimeDuration = 2.0
def flip_camera(self):
minimal_client = MinimalClientAsync()
response = minimal_client.send_request(True)
minimal_client.destroy_node()
def initAuton(self):
self.startTime = time()
self.turnStartTime = self.startTime + self.conePlacementDuration + 2
self.changed_stage = False
self.doAuton = True
self.flip_camera()
self.get_logger().info(f"STARTED AUTON AT {self.startTime}")
def loopAuton(self):
# self.taxiAuton()
self.coneAuton()
#self.turnAuton()
# CONE AUTOMATION STUFF
def publishCurrent(self):
self.cmds.points = [self.position_cmds]
self.publish_trajectory.publish(self.cmds)
def armExtensionManager(self, pos):
value = ''
if(pos == 0):
# RETRACT THE ARM
value = 'min'
self.get_logger().warn("ARM RETRACTED")
elif(pos == 1):
# EXTEND THE ARM
value = 'max'
self.get_logger().warn("ARM EXTENDED")
self.position_cmds.positions[int(self.joint_map['elevator_center_joint'])] = self.joint_limits["elevator_center_joint"][value]
self.position_cmds.positions[int(self.joint_map['elevator_outer_2_joint'])] = self.joint_limits["elevator_outer_2_joint"][value]
self.position_cmds.positions[int(self.joint_map['top_slider_joint'])] = self.joint_limits["top_slider_joint"][value]
self.publishCurrent()
def armHeightManager(self, pos):
value = ''
if(pos == 0):
# LOWER THE ARM
value = "min"
self.get_logger().warn("ARM LOWERED")
elif(pos == 1):
# RAISE THE ARM
value = "max"
self.get_logger().warn("ARM RAISED")
self.position_cmds.positions[int(self.joint_map['arm_roller_bar_joint'])] = self.joint_limits["arm_roller_bar_joint"][value]
self.position_cmds.positions[int(self.joint_map['elevator_outer_1_joint'])] = self.joint_limits["elevator_outer_1_joint"][value]
self.publishCurrent()
def gripperManager(self, pos):
value = ''
if(pos == 1):
# OPEN THE GRIPPER
value = 'min'
self.get_logger().warn("GRIPPER OPENED")
elif(pos == 0):
# CLOSE THE GRIPPER
value = 'max'
self.get_logger().warn("GRIPPER CLOSED")
self.position_cmds.positions[int(self.joint_map['top_gripper_left_arm_joint'])] = self.joint_limits["top_gripper_right_arm_joint"][value]
self.position_cmds.positions[int(self.joint_map['top_gripper_right_arm_joint'])] = self.joint_limits["top_gripper_right_arm_joint"][value]
self.publishCurrent()
def coneAuton(self):
elapsedTime = time() - self.startTime
totalDur = 0.0
for task in self.tasks:
totalDur += task['dur']
if elapsedTime < totalDur:
task['task'](task['arg'])
return
def taxiAuton(self):
elapsedTime = time() - self.startTime
if elapsedTime < self.taxiTimeDuration:
self.cmd.linear.x = 0.5
self.publish_twist.publish(self.cmd)
else:
return
def stop(self, x):
self.cmd.linear.x = 0.0
self.cmd.linear.y = 0.0
self.cmd.angular.z = 0.0
self.publish_twist.publish(self.cmd)
def goBackwards(self, speed):
self.cmd.linear.x = speed
self.publish_twist.publish(self.cmd)
self.get_logger().warn("GOING BACKWARDS")
def turnAround(self, angVel):
self.turnCmd.angular.z = angVel
self.publish_twist.publish(self.turnCmd)
self.get_logger().warn("TURNING")
def stopAuton(self):
self.cmd.linear.x = 0.0
# Publish twice to just to be safe
self.publish_twist.publish(self.cmd)
self.publish_twist.publish(self.cmd)
self.get_logger().info(f"STOPPED AUTON AT {time()}"),
self.doAuton = False
def listener_callback(self, msg):
# Check when any state has changed, enabled, disabled, auton, teleop, etc.
stage = str(msg.data).split("|")[0]
isdisabled = str(msg.data).split("|")[2]
if stage != self.stage or isdisabled != self.isdisabled:
self.changed_stage = True
self.stage = stage
self.isdisabled = isdisabled
# fms = str(msg.data).split("|")[1]
# Execute auton actions
if(stage.lower() == 'auton' and self.isdisabled == "False"):# and fms == 'True' ):
if self.changed_stage:
self.initAuton()
if self.doAuton:
self.loopAuton()
# We have moved out of auton enabled mode so stop if we are still running
else:
if self.doAuton:
self.stopAuton()
def main(args=None):
rclpy.init(args=args)
# minimal_client = MinimalClientAsync()
# response = minimal_client.send_request(True)
# # minimal_client.get_logger().info(
# # 'Result of add_two_ints: for %d + %d = %s' %
# # (True, response.success, response.message))
# # minimal_client.destroy_node()
# minimal_client.destroy_node()
stage_subscriber = StageSubscriber()
# stage_subscriber.send_request()
rclpy.spin(stage_subscriber)
# Destroy the node explicitly
# (optional - otherwise it will be done automatically
# when the garbage collector destroys the node object)
stage_subscriber.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
# create reader instance and open for reading
| 10,919 | Python | 34.454545 | 146 | 0.577617 |
RoboEagles4828/offseason2023/src/frc_auton/frc_auton/Auto_ros_bag/bag_0/metadata.yaml | rosbag2_bagfile_information:
version: 5
storage_identifier: sqlite3
duration:
nanoseconds: 33616431360
starting_time:
nanoseconds_since_epoch: 1679698398612800019
message_count: 72
topics_with_message_count:
- topic_metadata:
name: /real/swerve_controller/cmd_vel_unstamped
type: geometry_msgs/msg/Twist
serialization_format: cdr
offered_qos_profiles: ""
message_count: 9
- topic_metadata:
name: /real/joint_trajectory_controller/joint_trajectory
type: trajectory_msgs/msg/JointTrajectory
serialization_format: cdr
offered_qos_profiles: ""
message_count: 63
compression_format: ""
compression_mode: ""
relative_file_paths:
- bag_0_0.db3
files:
- path: bag_0_0.db3
starting_time:
nanoseconds_since_epoch: 1679698398612800019
duration:
nanoseconds: 33616431360
message_count: 72 | 930 | YAML | 28.093749 | 64 | 0.672043 |
RoboEagles4828/offseason2023/src/swerve_controller/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/offseason2023/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/offseason2023/src/edna_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/offseason2023/src/edna_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("edna_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,469 | Python | 34.853658 | 91 | 0.647379 |
RoboEagles4828/offseason2023/src/edna_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("edna_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/offseason2023/src/edna_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'
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.svo_file': 'live',
'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,150 | Python | 30.632352 | 91 | 0.597209 |
RoboEagles4828/offseason2023/src/edna_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('edna_description'))
xacro_file = os.path.join(description_pkg_path,'urdf', 'robots','edna.urdf.xacro')
edna_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('edna_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': edna_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": edna_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": edna_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],
)
)
# 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
]) | 6,682 | Python | 39.017964 | 114 | 0.652799 |
RoboEagles4828/offseason2023/src/edna_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_ros")
rtabmap_args = {
'rtabmap_args': '--delete_db_on_start',
'use_sim_time': use_sim_time,
'namespace': f'{NAMESPACE}_rtab',
# Frames
'frame_id': f'{NAMESPACE}/base_link',
'odom_frame_id': f'{NAMESPACE}/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,768 | Python | 34.379999 | 91 | 0.621041 |
RoboEagles4828/offseason2023/src/edna_bringup/launch/debugLayer.launch.py | from launch import LaunchDescription
from launch_ros.actions import Node
from ament_index_python.packages import get_package_share_directory
from launch.substitutions import LaunchConfiguration, PythonExpression
from launch.event_handlers import OnProcessExit
from launch.actions import DeclareLaunchArgument, ExecuteProcess, RegisterEventHandler
from launch.conditions import IfCondition
import os
def generate_launch_description():
bringup_pkg_path = os.path.join(get_package_share_directory('edna_bringup'))
use_sim_time = LaunchConfiguration('use_sim_time')
namespace = LaunchConfiguration('namespace')
enable_rviz = LaunchConfiguration('enable_rviz')
enable_foxglove = LaunchConfiguration('enable_foxglove')
enable_debugger_gui = LaunchConfiguration('enable_debugger_gui')
enable_joint_state_publisher = LaunchConfiguration('enable_joint_state_publisher')
rviz_file = LaunchConfiguration('rviz_file')
foxglove = Node(
package='foxglove_bridge',
executable='foxglove_bridge',
namespace=namespace,
parameters=[{
'port': 8765,
'use_sim_time': use_sim_time
}],
condition=IfCondition(enable_foxglove)
)
parse_script = os.path.join(bringup_pkg_path, 'scripts', 'parseRviz.py')
parseRvizFile = ExecuteProcess(cmd=["python3", parse_script, rviz_file, namespace])
rviz2 = Node(
package='rviz2',
name='rviz2',
namespace=namespace,
executable='rviz2',
parameters=[{ 'use_sim_time': use_sim_time }],
output='screen',
arguments=[["-d"], [rviz_file]],
condition=IfCondition(enable_rviz)
)
rviz2_delay = RegisterEventHandler(
event_handler=OnProcessExit(
target_action=parseRvizFile,
on_exit=[rviz2],
)
)
debugger_gui = Node(
package='edna_debugger',
namespace=namespace,
executable='debugger',
name='debugger',
output='screen',
parameters=[{
'use_sim_time': use_sim_time,
'publish_default_velocities': 'true',
'source_list': ['joint_states']
}],
condition=IfCondition(enable_debugger_gui),
)
# Starts Joint State Publisher GUI for rviz (conflicts with edna_debugger)
joint_state_publisher_gui = Node (
package='joint_state_publisher_gui',
namespace=namespace,
executable='joint_state_publisher_gui',
output='screen',
parameters=[{
'use_sim_time': use_sim_time,
'publish_default_velocities': True,
}],
condition=IfCondition(enable_joint_state_publisher),
)
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(
'enable_rviz',
default_value='true',
description='enables rviz'),
DeclareLaunchArgument(
'rviz_file',
default_value='',
description='The config file for rviz'),
DeclareLaunchArgument(
'enable_foxglove',
default_value='true',
description='enables foxglove bridge'),
DeclareLaunchArgument(
'enable_debugger_gui',
default_value='false',
description='enables the debugger gui tool'),
DeclareLaunchArgument(
'enable_joint_state_publisher',
default_value='false',
description='enables the joint state publisher tool'),
foxglove,
parseRvizFile,
rviz2_delay,
debugger_gui,
joint_state_publisher_gui,
]) | 3,908 | Python | 33.901785 | 87 | 0.620778 |
RoboEagles4828/offseason2023/src/edna_bringup/launch/real-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
def generate_launch_description():
bringup_path = get_package_share_directory("edna_bringup")
rviz_file = os.path.join(bringup_path, 'config', 'real.rviz')
common = {
'use_sim_time': 'false',
'namespace': 'real',
'forward_command_controller': 'false',
}
debug_launch_args = common | {
'enable_rviz': 'true',
'enable_foxglove': 'false',
'enable_debugger_gui': 'true',
'rviz_file': rviz_file
}
debug_layer = IncludeLaunchDescription(
PythonLaunchDescriptionSource([os.path.join(
bringup_path,'launch','debugLayer.launch.py'
)]), launch_arguments=debug_launch_args.items())
# Launch!
return LaunchDescription([
debug_layer,
]) | 1,037 | Python | 31.437499 | 75 | 0.644166 |
RoboEagles4828/offseason2023/src/edna_bringup/launch/real.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
def generate_launch_description():
bringup_path = get_package_share_directory("edna_bringup")
joystick_file = os.path.join(bringup_path, 'config', 'xbox-real.yaml')
common = { 'use_sim_time': 'false', 'namespace': 'real' }
control_launch_args = common | {
'use_ros2_control': 'true',
'hardware_plugin': 'swerve_hardware/RealDriveHardware',
}
teleoplaunch_args = common | {
'joystick_file': joystick_file,
'enable_joy': 'false'
}
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())
# Launch!
return LaunchDescription([
control_layer,
teleop_layer,
])
| 1,347 | Python | 34.473683 | 75 | 0.651819 |
RoboEagles4828/offseason2023/src/edna_bringup/scripts/parseRviz.py | import sys
import yaml
import os
# NAMESPACE = os.environ.get('ROS_NAMESPACE') if 'ROS_NAMESPACE' in os.environ else 'default'
def processRvizFileForNamespace(rviz_file, NAMESPACE):
rviz_data = None
raw_rviz_data = None
with open(rviz_file, 'r') as stream:
raw_rviz_data = stream.read()
rviz_data = yaml.safe_load(raw_rviz_data)
# Get the namespace value from the rviz file
current_namespace = None
if rviz_data:
for display in rviz_data['Visualization Manager']['Displays']:
for k, v in display.items():
if 'Topic' in k and 'Value' in v:
segs = v['Value'].split('/')
if len(segs) > 1:
current_namespace = segs[1]
break
if current_namespace:
print('Found namespace: ', current_namespace)
print(f"mapping {current_namespace} -> {NAMESPACE}")
new_rviz_data = yaml.safe_load(raw_rviz_data.replace(current_namespace, NAMESPACE))
with open(rviz_file, 'w') as stream:
yaml.dump(new_rviz_data, stream)
else:
with open('err', 'w') as stream:
stream.write("Couldn't find namespace in rviz file")
if __name__ == "__main__":
processRvizFileForNamespace(sys.argv[1], sys.argv[2]) | 1,314 | Python | 33.605262 | 93 | 0.590563 |
RoboEagles4828/offseason2023/src/edna_bringup/config/controllers.yaml | /*:
controller_manager:
ros__parameters:
update_rate: 20 # Hz
joint_state_broadcaster:
type: joint_state_broadcaster/JointStateBroadcaster
swerve_controller:
type: swerve_controller/SwerveController
forward_position_controller:
type: position_controllers/JointGroupPositionController
forward_velocity_controller:
type: velocity_controllers/JointGroupVelocityController
joint_trajectory_controller:
type: joint_trajectory_controller/JointTrajectoryController
swerve_controller:
ros__parameters:
#Used to scale velocity
chassis_length_meters: 0.6032
chassis_width_meters: 0.6032
wheel_radius_meters: 0.0508
max_wheel_angular_velocity: 100.0
#If no new twist commands are created in 1 second the robot will halt
cmd_vel_timeout_seconds: 1.0
use_stamped_vel: false
front_left_wheel_joint: front_left_wheel_joint
front_right_wheel_joint: front_right_wheel_joint
rear_left_wheel_joint: rear_left_wheel_joint
rear_right_wheel_joint: rear_right_wheel_joint
front_left_axle_joint: front_left_axle_joint
front_right_axle_joint: front_right_axle_joint
rear_left_axle_joint: rear_left_axle_joint
rear_right_axle_joint: rear_right_axle_joint
linear.x.has_velocity_limits: false
linear.x.has_acceleration_limits: true
linear.x.has_jerk_limits: false
linear.x.max_velocity: 2.0
linear.x.min_velocity: -2.0
linear.x.max_acceleration: 3.0
linear.x.min_acceleration: -3.0
linear.x.max_jerk: 5.0
linear.x.min_jerk: -5.0
linear.y.has_velocity_limits: false
linear.y.has_acceleration_limits: true
linear.y.has_jerk_limits: false
linear.y.max_velocity: 2.0
linear.y.min_velocity: -2.0
linear.y.max_acceleration: 3.0
linear.y.min_acceleration: -3.0
linear.y.max_jerk: 5.0
linear.y.min_jerk: -5.0
angular.z.has_velocity_limits: false
angular.z.has_acceleration_limits: true
angular.z.has_jerk_limits: false
angular.z.max_velocity: 3.0
angular.z.min_velocity: -3.0
angular.z.max_acceleration: 3.0
angular.z.min_acceleration: -3.0
angular.z.max_jerk: 5.0
angular.z.min_jerk: -5.0
forward_position_controller:
ros__parameters:
joints:
- 'front_left_axle_joint'
- 'front_right_axle_joint'
- 'rear_left_axle_joint'
- 'rear_right_axle_joint'
- 'arm_roller_bar_joint'
- 'elevator_outer_1_joint'
- 'elevator_center_joint'
- 'elevator_outer_2_joint'
- 'top_slider_joint'
- 'top_gripper_left_arm_joint'
- 'top_gripper_right_arm_joint'
- 'bottom_intake_joint'
forward_velocity_controller:
ros__parameters:
joints:
- 'front_left_wheel_joint'
- 'front_right_wheel_joint'
- 'rear_left_wheel_joint'
- 'rear_right_wheel_joint'
joint_trajectory_controller:
ros__parameters:
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'
command_interfaces:
- position
state_interfaces:
- position
- velocity
state_publish_rate: 50.0
action_monitor_rate: 20.0
allow_partial_joints_goal: false
open_loop_control: true
constraints:
stopped_velocity_tolerance: 0.01
goal_time: 0.0
| 3,706 | YAML | 28.188976 | 76 | 0.627361 |
RoboEagles4828/offseason2023/src/edna_bringup/config/xbox-sim.yaml | /*:
teleop_twist_joy_node:
ros__parameters:
require_enable_button: false
axis_linear: # Left thumb stick vertical
x: 1
y: 0
scale_linear:
x: 1.0
y: 1.0
scale_linear_turbo:
x: 2.5
y: 2.5
axis_angular: # Right thumb stick horizontal
yaw: 3
scale_angular:
yaw: -1.0
scale_angular_turbo:
yaw: -2.2
enable_turbo_button: 5
enable_field_oriented_button: 7
offset: 0.5
| 522 | YAML | 17.678571 | 51 | 0.5 |
RoboEagles4828/offseason2023/src/edna_bringup/config/xbox-real.yaml | /*:
teleop_twist_joy_node:
ros__parameters:
require_enable_button: false
axis_linear: # Left thumb stick vertical
x: 1
y: 0
scale_linear: #1/10000 to offset shifted 0 in /joystick-data
x: 0.0001
y: 0.0001
scale_linear_turbo:
x: 0.0004
y: 0.0004
axis_angular: # Right thumb stick horizontal
yaw: 3
scale_angular: #negative to fix turning direction
yaw: -0.0001
scale_angular_turbo:
yaw: -0.0002
enable_turbo_button: 5
enable_field_oriented_button: 7
offset: -0.25 | 610 | YAML | 24.458332 | 66 | 0.565574 |
RoboEagles4828/offseason2023/src/edna_bringup/config/teleop-control.yaml | controller_mapping:
A: 0
B: 1
X: 2
Y: 3
LB: 4
RB: 5
squares: 6
menu: 7
xbox: 8
LSin: 9
RSin: 10
leftTriggerAxis: 2
rightTriggerAxis: 5
joint_limits:
arm_roller_bar_joint:
min: 0.0
max: 0.07
elevator_center_joint:
min: 0.0
max: 0.56
elevator_outer_1_joint:
min: 0.0
max: 0.2
elevator_outer_2_joint:
min: 0.0
max: 0.56
top_gripper_right_arm_joint:
min: -0.9
max: 0.0
top_gripper_left_arm_joint:
min: -0.9
max: 0.0
top_slider_joint:
min: 0.0
max: 0.30
bottom_intake_joint:
min: 0.0
max: 1.52
joint_mapping:
arm_roller_bar_joint: 0
elevator_center_joint: 1
elevator_outer_1_joint: 2
elevator_outer_2_joint: 3
top_gripper_right_arm_joint: 4
top_gripper_left_arm_joint: 5
top_slider_joint: 6
bottom_intake_joint: 7
function_mapping:
elevator_loading_station:
button: "RSin"
toggle: true
skis_up:
button: "leftTriggerAxis"
toggle: true
elevator_mid_level:
button: "LB"
toggle: true
elevator_high_level:
button: "X"
toggle: true
top_gripper_control:
button: "A"
toggle: true
elevator_pivot_control:
button: "Y"
toggle: true
top_slider_control:
button: "B"
toggle: true | 1,278 | YAML | 17.271428 | 32 | 0.606416 |
RoboEagles4828/offseason2023/src/edna_debugger/setup.py | from setuptools import setup
package_name = 'edna_debugger'
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='GUI Robot Control Debugger',
license='Apache License 2.0',
tests_require=['pytest'],
entry_points={
'console_scripts': [
'debugger = edna_debugger.debugger:main'
],
},
)
| 674 | Python | 23.999999 | 53 | 0.60089 |
RoboEagles4828/offseason2023/src/edna_debugger/edna_debugger/flow_layout.py | # Implement a FlowLayout so sliders move around in a grid as the window is
# resized. Originally taken from:
# https://forum.qt.io/topic/109408/is-there-a-qt-layout-grid-that-can-dynamically-change-row-and-column-counts-to-best-fit-the-space/2
# with the license:
#
# This file taken from
# https://code.qt.io/cgit/qt/qtbase.git/tree/examples/widgets/layouts/flowlayout/flowlayout.cpp?h=5.13
# Modified/adapted by jon, 10/07/2019, to translate into Python/PyQt
#
# Copyright (C) 2016 The Qt Company Ltd.
# Contact: https://www.qt.io/licensing/
#
# This file is part of the examples of the Qt Toolkit.
#
# $QT_BEGIN_LICENSE:BSD$
# Commercial License Usage
# Licensees holding valid commercial Qt licenses may use this file in
# accordance with the commercial license agreement provided with the
# Software or, alternatively, in accordance with the terms contained in
# a written agreement between you and The Qt Company. For licensing terms
# and conditions see https://www.qt.io/terms-conditions. For further
# information use the contact form at https://www.qt.io/contact-us.
#
# BSD License Usage
# Alternatively, you may use this file under the terms of the BSD license
# as follows:
#
# "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 The Qt Company Ltd 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
# OWNER 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."
#
# $QT_END_LICENSE$
#
from python_qt_binding.QtCore import Qt
from python_qt_binding.QtCore import QPoint
from python_qt_binding.QtCore import QRect
from python_qt_binding.QtCore import QSize
from python_qt_binding.QtWidgets import QLayout
from python_qt_binding.QtWidgets import QSizePolicy
from python_qt_binding.QtWidgets import QStyle
class FlowLayout(QLayout):
def __init__(self, parent=None, margin=-1, hSpacing=-1, vSpacing=-1):
super().__init__(parent)
self.itemList = list()
self.m_hSpace = hSpacing
self.m_vSpace = vSpacing
self.setContentsMargins(margin, margin, margin, margin)
def __del__(self):
# copied for consistency, not sure this is needed or ever called
item = self.takeAt(0)
while item:
item = self.takeAt(0)
def addItem(self, item):
self.itemList.append(item)
def horizontalSpacing(self):
if self.m_hSpace >= 0:
return self.m_hSpace
else:
return self.smartSpacing(QStyle.PM_LayoutHorizontalSpacing)
def verticalSpacing(self):
if self.m_vSpace >= 0:
return self.m_vSpace
else:
return self.smartSpacing(QStyle.PM_LayoutVerticalSpacing)
def count(self):
return len(self.itemList)
def itemAt(self, index):
if 0 <= index < len(self.itemList):
return self.itemList[index]
return None
def takeAt(self, index):
if 0 <= index < len(self.itemList):
return self.itemList.pop(index)
return None
def expandingDirections(self):
return Qt.Orientations(Qt.Orientation(0))
def hasHeightForWidth(self):
return True
def heightForWidth(self, width):
return self.doLayout(QRect(0, 0, width, 0), True)
def setGeometry(self, rect):
super().setGeometry(rect)
self.doLayout(rect, False)
def sizeHint(self):
return self.minimumSize()
def minimumSize(self):
size = QSize()
for item in self.itemList:
size = size.expandedTo(item.minimumSize())
margins = self.contentsMargins()
size += QSize(margins.left() + margins.right(), margins.top() + margins.bottom())
return size
def smartSpacing(self, pm):
parent = self.parent()
if not parent:
return -1
elif parent.isWidgetType():
return parent.style().pixelMetric(pm, None, parent)
return parent.spacing()
def doLayout(self, rect, testOnly):
left, top, right, bottom = self.getContentsMargins()
effectiveRect = rect.adjusted(+left, +top, -right, -bottom)
x = effectiveRect.x()
y = effectiveRect.y()
lineHeight = 0
for item in self.itemList:
wid = item.widget()
spaceX = self.horizontalSpacing()
if spaceX == -1:
spaceX = wid.style().layoutSpacing(QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Horizontal)
spaceY = self.verticalSpacing()
if spaceY == -1:
spaceY = wid.style().layoutSpacing(QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Vertical)
nextX = x + item.sizeHint().width() + spaceX
if nextX - spaceX > effectiveRect.right() and lineHeight > 0:
x = effectiveRect.x()
y = y + lineHeight + spaceY
nextX = x + item.sizeHint().width() + spaceX
lineHeight = 0
if not testOnly:
item.setGeometry(QRect(QPoint(x, y), item.sizeHint()))
x = nextX
lineHeight = max(lineHeight, item.sizeHint().height())
return y + lineHeight - rect.y() + bottom | 6,445 | Python | 35.834286 | 134 | 0.672149 |
RoboEagles4828/offseason2023/src/edna_debugger/edna_debugger/debugger.py |
import argparse
import random
import signal
import sys
import threading
import rclpy
from python_qt_binding.QtCore import pyqtSlot
from python_qt_binding.QtCore import Qt
from python_qt_binding.QtCore import Signal
from python_qt_binding.QtGui import QFont
from python_qt_binding.QtWidgets import QApplication
from python_qt_binding.QtWidgets import QFormLayout
from python_qt_binding.QtWidgets import QGridLayout
from python_qt_binding.QtWidgets import QHBoxLayout
from python_qt_binding.QtWidgets import QLabel
from python_qt_binding.QtWidgets import QLineEdit
from python_qt_binding.QtWidgets import QMainWindow
from python_qt_binding.QtWidgets import QPushButton
from python_qt_binding.QtWidgets import QSlider
from python_qt_binding.QtWidgets import QScrollArea
from python_qt_binding.QtWidgets import QVBoxLayout
from python_qt_binding.QtWidgets import QWidget
from edna_debugger.joint_state_publisher import JointStatePublisher
from edna_debugger.flow_layout import FlowLayout
RANGE = 10000
LINE_EDIT_WIDTH = 45
SLIDER_WIDTH = 200
INIT_NUM_SLIDERS = 7 # Initial number of sliders to show in window
# Defined by style - currently using the default style
DEFAULT_WINDOW_MARGIN = 11
DEFAULT_CHILD_MARGIN = 9
DEFAULT_BTN_HEIGHT = 25
DEFAULT_SLIDER_HEIGHT = 64 # Is the combination of default heights in Slider
# Calculate default minimums for window sizing
MIN_WIDTH = SLIDER_WIDTH + DEFAULT_CHILD_MARGIN * 4 + DEFAULT_WINDOW_MARGIN * 2
MIN_HEIGHT = DEFAULT_BTN_HEIGHT * 2 + DEFAULT_WINDOW_MARGIN * 2 + DEFAULT_CHILD_MARGIN * 2
PNEUMATICS_JOINTS = [
'arm_roller_bar_joint',
'top_slider_joint',
'top_gripper_left_arm_joint',
'bottom_intake_joint'
]
class Button(QWidget):
def __init__(self, name):
super().__init__()
self.joint_layout = QVBoxLayout()
self.row_layout = QHBoxLayout()
font = QFont("Helvetica", 9, QFont.Bold)
self.label = QLabel(name)
self.label.setFont(font)
self.row_layout.addWidget(self.label)
self.joint_layout.addLayout(self.row_layout)
self.button = QPushButton('toggle', self)
self.button.setCheckable(True)
self.joint_layout.addWidget(self.button)
self.setLayout(self.joint_layout)
def remove(self):
self.joint_layout.remove_widget(self.button)
self.button.setParent(None)
self.row_layout.removeWidget(self.display)
self.display.setParent(None)
self.row_layout.removeWidget(self.label)
self.label.setParent(None)
self.row_layout.setParent(None)
class Slider(QWidget):
def __init__(self, name):
super().__init__()
self.joint_layout = QVBoxLayout()
# top row
self.row_layout_top = QHBoxLayout()
font = QFont("Helvetica", 9, QFont.Bold)
self.label = QLabel(name)
self.label.setFont(font)
self.row_layout_top.addWidget(self.label)
self.joint_layout.addLayout(self.row_layout_top)
# subscribing row
self.row_layout_sub = QHBoxLayout()
self.display_sub = QLineEdit("0.00")
self.display_sub.setAlignment(Qt.AlignRight)
self.display_sub.setFont(font)
self.display_sub.setReadOnly(True)
self.display_sub.setFixedWidth(LINE_EDIT_WIDTH)
self.row_layout_sub.addWidget(self.display_sub)
self.slider_sub = QSlider(Qt.Horizontal)
self.slider_sub.setFont(font)
self.slider_sub.setRange(0, RANGE)
self.slider_sub.setValue(int(RANGE / 2))
self.slider_sub.setFixedWidth(SLIDER_WIDTH)
self.row_layout_sub.addWidget(self.slider_sub)
self.joint_layout.addLayout(self.row_layout_sub)
# publishing row
self.row_layout_pub = QHBoxLayout()
self.display_pub = QLineEdit("0.00")
self.display_pub.setAlignment(Qt.AlignRight)
self.display_pub.setFont(font)
self.display_pub.setReadOnly(False)
self.display_pub.setFixedWidth(LINE_EDIT_WIDTH)
self.row_layout_pub.addWidget(self.display_pub)
self.slider_pub = QSlider(Qt.Horizontal)
self.slider_pub.setFont(font)
self.slider_pub.setRange(0, RANGE)
self.slider_pub.setValue(int(RANGE / 2))
self.slider_pub.setFixedWidth(SLIDER_WIDTH)
self.row_layout_pub.addWidget(self.slider_pub)
self.joint_layout.addLayout(self.row_layout_pub)
self.setLayout(self.joint_layout)
def remove(self):
self.joint_layout.removeWidget(self.slider)
self.slider.setParent(None)
self.row_layout.removeWidget(self.display)
self.display.setParent(None)
self.row_layout.removeWidget(self.label)
self.label.setParent(None)
self.row_layout.setParent(None)
class JointStatePublisherGui(QMainWindow):
sliderUpdateTrigger = Signal()
initialize = Signal()
def __init__(self, title, jsp : JointStatePublisher):
super(JointStatePublisherGui, self).__init__()
self.joint_map = {}
self.setWindowTitle(title)
# Button for randomizing the sliders
self.rand_button = QPushButton('Randomize', self)
self.rand_button.clicked.connect(self.randomizeEvent)
# Button for centering the sliders
self.ctr_button = QPushButton('Center', self)
self.ctr_button.clicked.connect(self.centerEvent)
# Button for resetting the joint butttons
self.reset_button = QPushButton('Reset Pistons', self)
self.reset_button.clicked.connect(self.resetButtons)
# Scroll area widget contents - layout
self.scroll_layout = FlowLayout()
# Scroll area widget contents
self.scroll_widget = QWidget()
self.scroll_widget.setLayout(self.scroll_layout)
# Scroll area for sliders
self.scroll_area = QScrollArea()
self.scroll_area.setWidgetResizable(True)
self.scroll_area.setWidget(self.scroll_widget)
# Main layout
self.main_layout = QVBoxLayout()
# Add buttons and scroll area to main layout
self.main_layout.addWidget(self.rand_button)
self.main_layout.addWidget(self.ctr_button)
self.main_layout.addWidget(self.reset_button)
self.main_layout.addWidget(self.scroll_area)
# central widget
self.central_widget = QWidget()
self.central_widget.setLayout(self.main_layout)
self.setCentralWidget(self.central_widget)
self.jsp = jsp
self.jsp.set_source_update_cb(self.sliderUpdateCb)
self.jsp.set_robot_description_update_cb(self.initializeCb)
self.running = True
self.sliders = {}
self.buttons = {}
# Setup signal for initializing the window
self.initialize.connect(self.initializeSliders)
# Set up a signal for updating the sliders based on external joint info
self.sliderUpdateTrigger.connect(self.updateSliders)
# Tell self to draw sliders in case the JointStatePublisher already has a robot_description
self.initialize.emit()
def initializeSliders(self):
self.joint_map = {}
for sl, _ in self.sliders.items():
self.scroll_layout.removeWidget(sl)
sl.remove()
### Generate sliders ###
for name in self.jsp.joint_list:
if name not in self.jsp.free_joints_sub:
continue
joint = self.jsp.free_joints_sub[name]
if joint['min'] == joint['max']:
continue
if (name in PNEUMATICS_JOINTS):
button = Button(name)
self.joint_map[name] = {'button': button.button, 'joint': joint}
self.scroll_layout.addWidget(button)
button.button.toggled.connect(lambda event,name=name: self.onInputValueChanged(name))
self.buttons[button] = button
else:
slider = Slider(name)
self.joint_map[name] = {'display_sub': slider.display_sub, 'slider_sub': slider.slider_sub, 'display_pub': slider.display_pub, 'slider_pub': slider.slider_pub, 'joint': joint}
self.scroll_layout.addWidget(slider)
slider.display_pub.textEdited.connect(lambda event,name=name: self.makeSliderEqualToText(name))
slider.slider_pub.valueChanged.connect(lambda event,name=name: self.makeTextEqualToSlider(name))
self.sliders[slider] = slider
# Set zero positions read from parameters
self.centerEvent(None)
# Set size of min size of window based on number of sliders.
if len(self.sliders) >= INIT_NUM_SLIDERS: # Limits min size to show INIT_NUM_SLIDERS
num_sliders = INIT_NUM_SLIDERS
else:
num_sliders = len(self.sliders)
scroll_layout_height = num_sliders * DEFAULT_SLIDER_HEIGHT
scroll_layout_height += (num_sliders + 1) * DEFAULT_CHILD_MARGIN
self.setMinimumSize(MIN_WIDTH, scroll_layout_height + MIN_HEIGHT)
self.sliderUpdateTrigger.emit()
def sliderUpdateCb(self):
self.sliderUpdateTrigger.emit()
def initializeCb(self):
self.initialize.emit()
# def onButtonClicked(self, name):
# # self.jsp.get_logger().info("button changed")
# joint_info = self.joint_map[name]
# buttonValue = 1 if joint_info['button'].isChecked() == True else 0
# joint_info['joint']['position'] = buttonValue
# joint_info['display'].setText(str(buttonValue))
# def onSliderTextEdited(self, slider, joint):
# self.jsp.get_logger().info(slider.display.text())
# slider.slider1.setSliderPosition(self.valueToSlider(float(slider.display.displayText()), joint))
def makeSliderEqualToText(self, name):
joint_info = self.joint_map[name]
textvalue = joint_info['display_pub'].text()
try:
joint_info['slider_pub'].setValue(self.valueToSlider(float(textvalue), joint_info['joint']))
self.onInputValueChanged(name)
except:
pass
def makeTextEqualToSlider(self, name):
joint_info = self.joint_map[name]
slidervalue = joint_info['slider_pub'].value()
joint_info['display_pub'].setText(str(round(self.sliderToValue(slidervalue, joint_info['joint']), 2)))
self.onInputValueChanged(name)
def onInputValueChanged(self, name):
# A slider value was changed, but we need to change the joint_info metadata.
joint_info = self.joint_map[name]
if ('slider_pub' in joint_info):
slidervalue = joint_info['slider_pub'].value()
joint = joint_info['joint']
if 'wheel' in name:
self.jsp.free_joints_pub[name]['velocity'] = self.sliderToValue(slidervalue, joint)
else:
self.jsp.free_joints_pub[name]['position'] = self.sliderToValue(slidervalue, joint)
elif ('button' in joint_info):
buttonValue = joint_info['joint']['max'] if joint_info['button'].isChecked() == True else joint_info['joint']['min']
self.jsp.free_joints_pub[name]['position'] = buttonValue
@pyqtSlot()
def updateSliders(self):
for name, joint_info in self.joint_map.items():
joint = joint_info['joint']
if ('slider_sub' in joint_info):
if 'wheel' in name:
slidervalue = self.valueToSlider(joint['velocity'], joint)
else:
slidervalue = self.valueToSlider(joint['position'], joint)
joint_info['slider_sub'].setValue(slidervalue)
joint_info['display_sub'].setText(str(round(self.sliderToValue(slidervalue, joint), 2)))
elif ('button' in joint_info):
buttonvalue = True if joint['position'] == joint['max'] else False
if (joint_info['button'].isChecked() == buttonvalue):
joint_info['button'].setStyleSheet('background-color: green')
else:
joint_info['button'].setStyleSheet('background-color: yellow')
def resetButtons(self, event):
self.jsp.get_logger().info("Toggling off")
for name, joint_info in self.joint_map.items():
if('button' in joint_info):
if(joint_info['button'].isChecked()):
joint_info['button'].setChecked(False)
def centerEvent(self, event):
self.jsp.get_logger().info("Centering")
for name, joint_info in self.joint_map.items():
if('slider' in joint_info):
joint = joint_info['joint']
joint_info['slider'].setValue(self.valueToSlider(joint['zero'], joint))
def randomizeEvent(self, event):
self.jsp.get_logger().info("Randomizing")
for name, joint_info in self.joint_map.items():
if('slider' in joint_info):
joint = joint_info['joint']
joint_info['slider'].setValue(
self.valueToSlider(random.uniform(joint['min'], joint['max']), joint))
def valueToSlider(self, value, joint):
# return int(value * 5000)
return int((value - joint['min']) * float(RANGE) / (joint['max'] - joint['min']))
def sliderToValue(self, slider, joint):
pctvalue = slider / float(RANGE)
return joint['min'] + (joint['max']-joint['min']) * pctvalue
def closeEvent(self, event):
self.running = False
def loop(self):
while self.running:
rclpy.spin_once(self.jsp, timeout_sec=0.1)
def main():
# Initialize rclpy with the command-line arguments
rclpy.init()
# Strip off the ROS 2-specific command-line arguments
stripped_args = rclpy.utilities.remove_ros_args(args=sys.argv)
parser = argparse.ArgumentParser()
parser.add_argument('urdf_file', help='URDF file to use', nargs='?', default=None)
# Parse the remaining arguments, noting that the passed-in args must *not*
# contain the name of the program.
parsed_args = parser.parse_args(args=stripped_args[1:])
app = QApplication(sys.argv)
jsp_gui = JointStatePublisherGui('Debugger',
JointStatePublisher(parsed_args.urdf_file))
jsp_gui.show()
threading.Thread(target=jsp_gui.loop).start()
signal.signal(signal.SIGINT, signal.SIG_DFL)
sys.exit(app.exec_())
if __name__ == '__main__':
main() | 14,516 | Python | 35.2925 | 191 | 0.640052 |
RoboEagles4828/offseason2023/src/edna_debugger/edna_debugger/joint_state_publisher.py | # Copyright (c) 2010, Willow Garage, Inc.
# All rights reserved.
#
# Software License Agreement (BSD License 2.0)
#
# 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 Willow Garage, Inc. 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 OWNER 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.
# Standard Python imports
import argparse
import math
import sys
import time
import xml.dom.minidom
# ROS 2 imports
import rclpy
import rclpy.node
from rcl_interfaces.msg import ParameterDescriptor, ParameterType
import sensor_msgs.msg
import std_msgs.msg
POSITION_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',
'front_left_axle_joint',
'front_right_axle_joint',
'rear_left_axle_joint',
'rear_right_axle_joint',
}
VELOCITY_JOINTS = [
'front_left_wheel_joint',
'front_right_wheel_joint',
'rear_left_wheel_joint',
'rear_right_wheel_joint',
]
class JointStatePublisher(rclpy.node.Node):
def get_param(self, name):
return self.get_parameter(name).value
def _init_joint(self, minval, maxval, zeroval):
joint = {'min': minval, 'max': maxval, 'zero': zeroval}
if self.pub_def_positions:
joint['position'] = zeroval
if self.pub_def_vels:
joint['velocity'] = 0.0
if self.pub_def_efforts:
joint['effort'] = 0.0
return joint
def init_collada(self, robot):
robot = robot.getElementsByTagName('kinematics_model')[0].getElementsByTagName('technique_common')[0]
for child in robot.childNodes:
if child.nodeType is child.TEXT_NODE:
continue
if child.localName == 'joint':
name = child.getAttribute('name')
if child.getElementsByTagName('revolute'):
joint = child.getElementsByTagName('revolute')[0]
else:
self.get_logger().warn('Unknown joint type %s', child)
continue
if joint:
limit = joint.getElementsByTagName('limits')[0]
minval = float(limit.getElementsByTagName('min')[0].childNodes[0].nodeValue)
maxval = float(limit.getElementsByTagName('max')[0].childNodes[0].nodeValue)
if minval == maxval: # this is a fixed joint
continue
self.joint_list.append(name)
minval *= math.pi/180.0
maxval *= math.pi/180.0
self.free_joints_sub[name] = self._init_joint(minval, maxval, 0.0)
self.free_joints_pub[name] = self.free_joints_sub[name]
def init_urdf(self, robot):
robot = robot.getElementsByTagName('robot')[0]
# Find all non-fixed joints
for child in robot.childNodes:
if child.nodeType is child.TEXT_NODE:
continue
if child.localName == 'joint':
jtype = child.getAttribute('type')
if jtype in ['fixed', 'floating', 'planar']:
continue
name = child.getAttribute('name')
self.joint_list.append(name)
if jtype == 'continuous':
if name in VELOCITY_JOINTS:
minval = -39.4 # this is not a good number i pulled it out of thin air
maxval = 39.4 # please someone calculate the actual thing using the circumference of the wheels and that stuff
else:
minval = -math.pi
maxval = math.pi
else:
try:
limit = child.getElementsByTagName('limit')[0]
minval = float(limit.getAttribute('lower'))
maxval = float(limit.getAttribute('upper'))
except:
self.get_logger().warn('%s is not fixed, nor continuous, but limits are not specified!' % name)
continue
safety_tags = child.getElementsByTagName('safety_controller')
if self.use_small and len(safety_tags) == 1:
tag = safety_tags[0]
if tag.hasAttribute('soft_lower_limit'):
minval = max(minval, float(tag.getAttribute('soft_lower_limit')))
if tag.hasAttribute('soft_upper_limit'):
maxval = min(maxval, float(tag.getAttribute('soft_upper_limit')))
mimic_tags = child.getElementsByTagName('mimic')
if self.use_mimic and len(mimic_tags) == 1:
tag = mimic_tags[0]
entry = {'parent': tag.getAttribute('joint')}
if tag.hasAttribute('multiplier'):
entry['factor'] = float(tag.getAttribute('multiplier'))
if tag.hasAttribute('offset'):
entry['offset'] = float(tag.getAttribute('offset'))
self.dependent_joints[name] = entry
continue
if name in self.dependent_joints:
continue
if self.zeros and name in self.zeros:
zeroval = self.zeros[name]
elif minval > 0 or maxval < 0:
zeroval = (maxval + minval)/2
else:
zeroval = 0
joint = self._init_joint(minval, maxval, zeroval)
if jtype == 'continuous':
joint['continuous'] = True
self.free_joints_sub[name] = joint
self.free_joints_pub[name] = joint.copy()
def configure_robot(self, description):
self.get_logger().debug('Got description, configuring robot')
try:
robot = xml.dom.minidom.parseString(description)
except xml.parsers.expat.ExpatError:
# If the description fails to parse for some reason, print an error
# and get out of here without doing further work. If we were
# already running with a description, we'll continue running with
# that older one.
self.get_logger().warn('Invalid robot_description given, ignoring')
return
# Make sure to clear out the old joints so we don't get duplicate joints
# on a new robot description.
self.free_joints_sub = {}
self.free_joints_pub = {}
self.joint_list = [] # for maintaining the original order of the joints
if robot.getElementsByTagName('COLLADA'):
self.init_collada(robot)
else:
self.init_urdf(robot)
if self.robot_description_update_cb is not None:
self.robot_description_update_cb()
def parse_dependent_joints(self):
dj = {}
dependent_joints = self.get_parameters_by_prefix('dependent_joints')
# get_parameters_by_prefix returned a dictionary of keynames like
# 'head.parent', 'head.offset', etc. that map to rclpy Parameter values.
# The rest of the code assumes that the dependent_joints dictionary is
# a map of name -> dict['parent': parent, factor: factor, offset: offset],
# where both factor and offset are optional. Thus we parse the values we
# got into that structure.
for name, param in dependent_joints.items():
# First split on the dots; there should be one and exactly one dot
split = name.split('.')
if len(split) != 2:
raise Exception("Invalid dependent_joint name '%s'" % (name))
newkey = split[0]
newvalue = split[1]
if newvalue not in ['parent', 'factor', 'offset']:
raise Exception("Invalid dependent_joint name '%s' (allowed values are 'parent', 'factor', and 'offset')" % (newvalue))
if newkey in dj:
dj[newkey].update({newvalue: param.value})
else:
dj[newkey] = {newvalue: param.value}
# Now ensure that there is at least a 'parent' in all keys
for name,outdict in dj.items():
if outdict.get('parent', None) is None:
raise Exception('All dependent_joints must at least have a parent')
return dj
def declare_ros_parameter(self, name, default, descriptor):
# When the automatically_declare_parameters_from_overrides parameter to
# rclpy.create_node() is True, then any parameters passed in on the
# command-line are automatically declared. In that case, calling
# node.declare_parameter() will raise an exception. However, in the case
# where a parameter is *not* overridden, we still want to declare it
# (so it shows up in "ros2 param list", for instance). Thus we always do
# a declaration and just ignore ParameterAlreadyDeclaredException.
try:
self.declare_parameter(name, default, descriptor)
except rclpy.exceptions.ParameterAlreadyDeclaredException:
pass
def __init__(self, urdf_file):
super().__init__('joint_state_publisher', automatically_declare_parameters_from_overrides=True)
self.declare_ros_parameter('publish_default_efforts', False, ParameterDescriptor(type=ParameterType.PARAMETER_BOOL))
self.declare_ros_parameter('publish_default_positions', True, ParameterDescriptor(type=ParameterType.PARAMETER_BOOL))
self.declare_ros_parameter('publish_default_velocities', False, ParameterDescriptor(type=ParameterType.PARAMETER_BOOL))
self.declare_ros_parameter('rate', 10, ParameterDescriptor(type=ParameterType.PARAMETER_INTEGER))
self.declare_ros_parameter('source_list', [], ParameterDescriptor(type=ParameterType.PARAMETER_STRING_ARRAY))
self.declare_ros_parameter('use_mimic_tags', True, ParameterDescriptor(type=ParameterType.PARAMETER_BOOL))
self.declare_ros_parameter('use_smallest_joint_limits', True, ParameterDescriptor(type=ParameterType.PARAMETER_BOOL))
self.declare_ros_parameter('delta', 0.0, ParameterDescriptor(type=ParameterType.PARAMETER_DOUBLE))
# In theory we would also declare 'dependent_joints' and 'zeros' here.
# Since rclpy doesn't support maps natively, though, we just end up
# letting 'automatically_declare_parameters_from_overrides' declare
# any parameters for us.
self.free_joints_sub = {}
self.free_joints_pub = {}
self.joint_list = [] # for maintaining the original order of the joints
self.dependent_joints = self.parse_dependent_joints()
self.use_mimic = self.get_param('use_mimic_tags')
self.use_small = self.get_param('use_smallest_joint_limits')
zeros = self.get_parameters_by_prefix('zeros')
# get_parameters_by_prefix() returns a map of name -> Parameter
# structures, but self.zeros is expected to be a list of name -> float;
# fix that here.
self.zeros = {k:v.value for (k, v) in zeros.items()}
self.pub_def_positions = self.get_param('publish_default_positions')
self.pub_def_vels = self.get_param('publish_default_velocities')
self.pub_def_efforts = self.get_param('publish_default_efforts')
self.robot_description_update_cb = None
if urdf_file is not None:
# If we were given a URDF file on the command-line, use that.
with open(urdf_file, 'r') as infp:
description = infp.read()
self.configure_robot(description)
else:
# Otherwise, subscribe to the '/robot_description' topic and wait
# for a callback there
self.get_logger().info('Waiting for robot_description to be published on the robot_description topic...')
self.create_subscription(std_msgs.msg.String, 'robot_description',
lambda msg: self.configure_robot(msg.data),
rclpy.qos.QoSProfile(depth=1, durability=rclpy.qos.QoSDurabilityPolicy.TRANSIENT_LOCAL))
self.delta = self.get_param('delta')
source_list = self.get_param('source_list')
self.sources = []
# for source in source_list:
# self.sources.append(self.create_subscription(sensor_msgs.msg.JointState, source, self.source_cb, 10))
# The source_update_cb will be called at the end of self.source_cb.
# The main purpose is to allow external observers (such as the
# joint_state_publisher_gui) to be notified when things are updated.
self.source_update_cb = None
# Override topic name here
self.pub_pos = self.create_publisher(std_msgs.msg.Float64MultiArray, 'forward_position_controller/commands', 10)
self.pub_vel = self.create_publisher(std_msgs.msg.Float64MultiArray, 'forward_velocity_controller/commands', 10)
self.create_subscription(sensor_msgs.msg.JointState, 'joint_states', self.source_cb, 10)
self.timer = self.create_timer(1.0 / self.get_param('rate'), self.timer_callback)
def source_cb(self, msg):
# self.get_logger().info("ran source callback")
for i in range(len(msg.name)):
name = msg.name[i]
if name not in self.free_joints_sub:
continue
if msg.position:
position = msg.position[i]
else:
position = None
if msg.velocity:
velocity = msg.velocity[i]
else:
velocity = None
if msg.effort:
effort = msg.effort[i]
else:
effort = None
joint = self.free_joints_sub[name]
if position is not None:
joint['position'] = position
if velocity is not None:
joint['velocity'] = velocity
if effort is not None:
joint['effort'] = effort
if self.source_update_cb is not None:
self.source_update_cb()
def set_source_update_cb(self, user_cb):
self.source_update_cb = user_cb
def set_robot_description_update_cb(self, user_cb):
self.robot_description_update_cb = user_cb
def timer_callback(self):
# Publish Joint States
msg = sensor_msgs.msg.JointState()
msg.header.stamp = self.get_clock().now().to_msg()
if self.delta > 0:
self.update(self.delta)
# Initialize msg.position, msg.velocity, and msg.effort.
has_position = False
has_velocity = False
has_effort = False
for name, joint in self.free_joints_pub.items():
if not has_position and 'position' in joint:
has_position = True
if not has_velocity and 'velocity' in joint:
has_velocity = True
if not has_effort and 'effort' in joint:
has_effort = True
num_joints = (len(self.free_joints_pub.items()) +
len(self.dependent_joints.items()))
if has_position:
msg.position = []
if has_velocity:
msg.velocity = []
if has_effort:
msg.effort = num_joints * [0.0]
for i, name in enumerate(self.joint_list):
msg.name.append(str(name))
joint = None
# Add Free Joint
if name in self.free_joints_pub:
joint = self.free_joints_pub[name]
factor = 1
offset = 0
# Add Dependent Joint
elif name in self.dependent_joints:
param = self.dependent_joints[name]
parent = param['parent']
factor = param.get('factor', 1.0)
offset = param.get('offset', 0.0)
# Handle recursive mimic chain
recursive_mimic_chain_joints = [name]
while parent in self.dependent_joints:
if parent in recursive_mimic_chain_joints:
error_message = 'Found an infinite recursive mimic chain'
self.get_logger().error(f'{error_message}: {recursive_mimic_chain_joints + [parent]}')
sys.exit(1)
recursive_mimic_chain_joints.append(parent)
param = self.dependent_joints[parent]
parent = param['parent']
offset += factor * param.get('offset', 0)
factor *= param.get('factor', 1)
joint = self.free_joints_pub[parent]
# the issue here is that its setting [i] either to the joint, or its skipping i in the list when we need it to be the next value.
# For some reason, [list].append() ends up putting way too many empty values that come from nowhere into the list.
# The best thing to do here would be having two separate iterators which only increment if the variable has a position or a velocity.
if has_position and 'position' in joint and name in POSITION_JOINTS:
msg.position.append(float(joint['position']) * factor + offset)
if has_velocity and 'velocity' in joint and name in VELOCITY_JOINTS:
msg.velocity.append(float(joint['velocity']) * factor)
if has_effort and 'effort' in joint:
msg.effort[i] = float(joint['effort'])
# Only publish non-empty messages
if not (msg.name or msg.position or msg.velocity or msg.effort):
return
pos_msg = std_msgs.msg.Float64MultiArray()
vel_msg = std_msgs.msg.Float64MultiArray()
pos_msg.data = msg.position
vel_msg.data = msg.velocity
self.pub_pos.publish(pos_msg)
self.pub_vel.publish(vel_msg)
def update(self, delta):
for name, joint in self.free_joints_sub.items():
forward = joint.get('forward', True)
if forward:
joint['position'] += delta
if joint['position'] > joint['max']:
if joint.get('continuous', False):
joint['position'] = joint['min']
else:
joint['position'] = joint['max']
joint['forward'] = not forward
else:
joint['position'] -= delta
if joint['position'] < joint['min']:
joint['position'] = joint['min']
joint['forward'] = not forward
def main():
# Initialize rclpy with the command-line arguments
rclpy.init()
# Strip off the ROS 2-specific command-line arguments
stripped_args = rclpy.utilities.remove_ros_args(args=sys.argv)
parser = argparse.ArgumentParser()
parser.add_argument('urdf_file', help='URDF file to use', nargs='?', default=None)
# Parse the remaining arguments, noting that the passed-in args must *not*
# contain the name of the program.
parsed_args = parser.parse_args(args=stripped_args[1:])
jsp = JointStatePublisher(parsed_args.urdf_file)
try:
rclpy.spin(jsp)
except KeyboardInterrupt:
pass
jsp.destroy_node()
rclpy.try_shutdown()
if __name__ == '__main__':
main()
| 20,839 | Python | 42.873684 | 145 | 0.595038 |
RoboEagles4828/offseason2023/isaac/README.md | # Isaac Sim Code and Assests | 28 | Markdown | 27.999972 | 28 | 0.785714 |
RoboEagles4828/offseason2023/isaac/exts/omni.isaac.edna/omni/isaac/edna/import_bot/__init__.py |
from omni.isaac.edna.import_bot.import_bot import ImportBot
from omni.isaac.edna.import_bot.import_bot_extension import ImportBotExtension
| 140 | Python | 34.249991 | 78 | 0.842857 |
RoboEagles4828/offseason2023/isaac/exts/omni.isaac.edna/omni/isaac/edna/import_bot/import_bot_extension.py | # Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import os
from omni.isaac.edna.base_sample import BaseSampleExtension
from omni.isaac.edna.import_bot.import_bot import ImportBot
import omni.ui as ui
from omni.isaac.ui.ui_utils import state_btn_builder
class ImportBotExtension(BaseSampleExtension):
def on_startup(self, ext_id: str):
super().on_startup(ext_id)
super().start_extension(
menu_name="Edna FRC",
submenu_name="",
name="Import URDF",
title="Load the URDF for Edna FRC 2023 Robot",
doc_link="",
overview="This loads the Edna robot into Isaac Sim.",
file_path=os.path.abspath(__file__),
sample=ImportBot(),
number_of_extra_frames=1
)
self.task_ui_elements = {}
frame = self.get_frame(index=0)
self.build_task_controls_ui(frame)
return
def _on_toggle_camera_button_event(self, val):
return
def build_task_controls_ui(self, frame):
with frame:
with ui.VStack(spacing=5):
# Update the Frame Title
frame.title = "Task Controls"
frame.visible = True
dict = {
"label": "Toggle Cameras",
"type": "button",
"a_text": "START",
"b_text": "STOP",
"tooltip": "Start the cameras",
"on_clicked_fn": self._on_toggle_camera_button_event,
}
self.task_ui_elements["Toggle Camera"] = state_btn_builder(**dict)
self.task_ui_elements["Toggle Camera"].enabled = False
| 2,080 | Python | 36.836363 | 82 | 0.597596 |
RoboEagles4828/offseason2023/isaac/exts/omni.isaac.edna/omni/isaac/edna/import_bot/import_bot.py | from omni.isaac.core.utils.stage import add_reference_to_stage
import omni.graph.core as og
import omni.usd
from omni.isaac.edna.base_sample import BaseSample
from omni.isaac.urdf import _urdf
from omni.isaac.core.robots import Robot
from omni.isaac.core.utils import prims
from omni.isaac.core.prims import GeometryPrim
from omni.isaac.core_nodes.scripts.utils import set_target_prims
# from omni.kit.viewport_legacy import get_default_viewport_window
# from omni.isaac.sensor import IMUSensor
from pxr import UsdPhysics, UsdShade, Sdf, Gf
import omni.kit.commands
import os
import numpy as np
import math
import carb
NAMESPACE = f"{os.environ.get('ROS_NAMESPACE')}" if 'ROS_NAMESPACE' in os.environ else 'default'
def set_drive_params(drive, stiffness, damping, max_force):
drive.GetStiffnessAttr().Set(stiffness)
drive.GetDampingAttr().Set(damping)
if(max_force != 0.0):
drive.GetMaxForceAttr().Set(max_force)
return
def add_physics_material_to_prim(prim, materialPath):
bindingAPI = UsdShade.MaterialBindingAPI.Apply(prim)
materialPrim = UsdShade.Material(materialPath)
bindingAPI.Bind(materialPrim, UsdShade.Tokens.weakerThanDescendants, "physics")
class ImportBot(BaseSample):
def __init__(self) -> None:
super().__init__()
return
def set_friction(self, robot_prim_path):
mtl_created_list = []
# Create a new material using OmniGlass.mdl
omni.kit.commands.execute(
"CreateAndBindMdlMaterialFromLibrary",
mdl_name="OmniPBR.mdl",
mtl_name="Rubber",
mtl_created_list=mtl_created_list,
)
# Get reference to created material
stage = omni.usd.get_context().get_stage()
mtl_prim = stage.GetPrimAtPath(mtl_created_list[0])
friction_material = UsdPhysics.MaterialAPI.Apply(mtl_prim)
friction_material.CreateDynamicFrictionAttr(1.0)
friction_material.CreateStaticFrictionAttr(1.0)
front_left_wheel_prim = stage.GetPrimAtPath(f"{robot_prim_path}/front_left_wheel_link/collisions")
front_right_wheel_prim = stage.GetPrimAtPath(f"{robot_prim_path}/front_right_wheel_link/collisions")
rear_left_wheel_prim = stage.GetPrimAtPath(f"{robot_prim_path}/rear_left_wheel_link/collisions")
rear_right_wheel_prim = stage.GetPrimAtPath(f"{robot_prim_path}/rear_right_wheel_link/collisions")
add_physics_material_to_prim(front_left_wheel_prim, mtl_prim)
add_physics_material_to_prim(front_right_wheel_prim, mtl_prim)
add_physics_material_to_prim(rear_left_wheel_prim, mtl_prim)
add_physics_material_to_prim(rear_right_wheel_prim, mtl_prim)
def setup_scene(self):
world = self.get_world()
world.get_physics_context().enable_gpu_dynamics(False)
world.scene.add_default_ground_plane()
self.setup_field()
# self.setup_perspective_cam()
self.setup_world_action_graph()
return
def setup_field(self):
world = self.get_world()
self.extension_path = os.path.abspath(__file__)
self.project_root_path = os.path.abspath(os.path.join(self.extension_path, "../../../../../../.."))
field = os.path.join(self.project_root_path, "assets/2023_field_cpu/FE-2023.usd")
add_reference_to_stage(usd_path=field,prim_path="/World/Field")
cone = os.path.join(self.project_root_path, "assets/2023_field_cpu/parts/GE-23700_JFH.usd")
cube = os.path.join(self.project_root_path, "assets/2023_field_cpu/parts/GE-23701_JFL.usd")
chargestation = os.path.join(self.project_root_path, "assets/ChargeStation-Copy/Assembly-1.usd")
add_reference_to_stage(chargestation, "/World/ChargeStation_1")
add_reference_to_stage(chargestation, "/World/ChargeStation_2")
add_reference_to_stage(cone, "/World/Cone_1")
add_reference_to_stage(cone, "/World/Cone_2")
add_reference_to_stage(cone, "/World/Cone_3")
add_reference_to_stage(cone, "/World/Cone_4")
# add_reference_to_stage(cone, "/World/Cone_5")
# add_reference_to_stage(cone, "/World/Cone_6")
# add_reference_to_stage(cone, "/World/Cone_7")
# add_reference_to_stage(cone, "/World/Cone_8")
cone_1 = GeometryPrim("/World/Cone_1","cone_1_view",position=np.array([1.20298,-0.56861,0.0]))
cone_2 = GeometryPrim("/World/Cone_2","cone_2_view",position=np.array([1.20298,3.08899,0.0]))
cone_3 = GeometryPrim("/World/Cone_3","cone_3_view",position=np.array([-1.20298,-0.56861,0.0]))
cone_4 = GeometryPrim("/World/Cone_4","cone_4_view",position=np.array([-1.20298,3.08899,0.0]))
chargestation_1 = GeometryPrim("/World/ChargeStation_1","cone_3_view",position=np.array([-4.20298,-0.56861,0.0]))
chargestation_2 = GeometryPrim("/World/ChargeStation_2","cone_4_view",position=np.array([4.20298,0.56861,0.0]))
add_reference_to_stage(cube, "/World/Cube_1")
add_reference_to_stage(cube, "/World/Cube_2")
add_reference_to_stage(cube, "/World/Cube_3")
add_reference_to_stage(cube, "/World/Cube_4")
# add_reference_to_stage(cube, "/World/Cube_5")
# add_reference_to_stage(cube, "/World/Cube_6")
# add_reference_to_stage(cube, "/World/Cube_7")
# add_reference_to_stage(cube, "/World/Cube_8")
cube_1 = GeometryPrim("/World/Cube_1","cube_1_view",position=np.array([1.20298,0.65059,0.121]))
cube_2 = GeometryPrim("/World/Cube_2","cube_2_view",position=np.array([1.20298,1.86979,0.121]))
cube_3 = GeometryPrim("/World/Cube_3","cube_3_view",position=np.array([-1.20298,0.65059,0.121]))
cube_4 = GeometryPrim("/World/Cube_4","cube_4_view",position=np.array([-1.20298,1.86979,0.121]))
async def setup_post_load(self):
self._world = self.get_world()
# self._world.get_physics_context().enable_gpu_dynamics(True)
self.robot_name = "edna"
self.extension_path = os.path.abspath(__file__)
self.project_root_path = os.path.abspath(os.path.join(self.extension_path, "../../../../../../.."))
self.path_to_urdf = os.path.join(self.extension_path, "../../../../../../../..", "src/edna_description/urdf/edna.urdf")
carb.log_info(self.path_to_urdf)
self._robot_prim_path = self.import_robot(self.path_to_urdf)
if self._robot_prim_path is None:
print("Error: failed to import robot")
return
self._robot_prim = self._world.scene.add(
Robot(prim_path=self._robot_prim_path, name=self.robot_name, position=np.array([0.0, 0.0, 0.3]), orientation=np.array([0.0, 0.0, 0.0, 1.0]))
)
self.configure_robot(self._robot_prim_path)
return
def import_robot(self, urdf_path):
import_config = _urdf.ImportConfig()
import_config.merge_fixed_joints = False
import_config.fix_base = False
import_config.make_default_prim = True
import_config.self_collision = False
import_config.create_physics_scene = False
import_config.import_inertia_tensor = True
import_config.default_drive_strength = 1047.19751
import_config.default_position_drive_damping = 52.35988
import_config.default_drive_type = _urdf.UrdfJointTargetType.JOINT_DRIVE_VELOCITY
import_config.distance_scale = 1.0
import_config.density = 0.0
result, prim_path = omni.kit.commands.execute( "URDFParseAndImportFile",
urdf_path=urdf_path,
import_config=import_config)
if result:
return prim_path
return None
def configure_robot(self, robot_prim_path):
w_sides = ['left', 'right']
l_sides = ['front', 'back']
stage = self._world.stage
chassis_name = f"swerve_chassis_link"
front_left_axle = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/{chassis_name}/front_left_axle_joint"), "angular")
front_right_axle = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/{chassis_name}/front_right_axle_joint"), "angular")
rear_left_axle = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/{chassis_name}/rear_left_axle_joint"), "angular")
rear_right_axle = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/{chassis_name}/rear_right_axle_joint"), "angular")
front_left_wheel = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/front_left_axle_link/front_left_wheel_joint"), "angular")
front_right_wheel = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/front_right_axle_link/front_right_wheel_joint"), "angular")
rear_left_wheel = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/rear_left_axle_link/rear_left_wheel_joint"), "angular")
rear_right_wheel = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/rear_right_axle_link/rear_right_wheel_joint"), "angular")
arm_roller_bar_joint = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/arm_elevator_leg_link/arm_roller_bar_joint"), "linear")
elevator_center_joint = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/elevator_outer_1_link/elevator_center_joint"), "linear")
elevator_outer_2_joint = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/elevator_center_link/elevator_outer_2_joint"), "linear")
elevator_outer_1_joint = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/arm_back_leg_link/elevator_outer_1_joint"), "angular")
top_gripper_left_arm_joint = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/top_gripper_bar_link/top_gripper_left_arm_joint"), "angular")
top_gripper_right_arm_joint = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/top_gripper_bar_link/top_gripper_right_arm_joint"), "angular")
top_slider_joint = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/elevator_outer_2_link/top_slider_joint"), "linear")
bottom_intake_joint = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"{robot_prim_path}/arm_elevator_leg_link/bottom_intake_joint"), "angular")
set_drive_params(front_left_axle, 1, 1000, 98.0)
set_drive_params(front_right_axle, 1, 1000, 98.0)
set_drive_params(rear_left_axle, 1, 1000, 98.0)
set_drive_params(rear_right_axle, 1, 1000, 98.0)
set_drive_params(front_left_wheel, 1, 1000, 98.0)
set_drive_params(front_right_wheel, 1, 1000, 98.0)
set_drive_params(rear_left_wheel, 1, 1000, 98.0)
set_drive_params(rear_right_wheel, 1, 1000, 98.0)
set_drive_params(arm_roller_bar_joint, 10000000, 100000, 98.0)
set_drive_params(elevator_center_joint, 10000000, 100000, 98.0)
set_drive_params(elevator_outer_1_joint, 10000000, 100000, 2000.0)
set_drive_params(elevator_outer_2_joint, 10000000, 100000, 98.0)
set_drive_params(top_gripper_left_arm_joint, 10000000, 100000, 98.0)
set_drive_params(top_gripper_right_arm_joint, 10000000, 100000, 98.0)
set_drive_params(top_slider_joint, 10000000, 100000, 98.0)
set_drive_params(bottom_intake_joint, 10000000, 100000, 98.0)
# self.create_lidar(robot_prim_path)
self.create_imu(robot_prim_path)
self.create_depth_camera(robot_prim_path)
self.setup_camera_action_graph(robot_prim_path)
self.setup_imu_action_graph(robot_prim_path)
self.setup_robot_action_graph(robot_prim_path)
self.set_friction(robot_prim_path)
return
def create_lidar(self, robot_prim_path):
lidar_parent = f"{robot_prim_path}/lidar_link"
lidar_path = "/lidar"
self.lidar_prim_path = lidar_parent + lidar_path
result, prim = omni.kit.commands.execute(
"RangeSensorCreateLidar",
path=lidar_path,
parent=lidar_parent,
min_range=0.4,
max_range=25.0,
draw_points=False,
draw_lines=True,
horizontal_fov=360.0,
vertical_fov=30.0,
horizontal_resolution=0.4,
vertical_resolution=4.0,
rotation_rate=0.0,
high_lod=False,
yaw_offset=0.0,
enable_semantics=False
)
return
def create_imu(self, robot_prim_path):
imu_parent = f"{robot_prim_path}/zed2i_imu_link"
imu_path = "/imu"
self.imu_prim_path = imu_parent + imu_path
result, prim = omni.kit.commands.execute(
"IsaacSensorCreateImuSensor",
path=imu_path,
parent=imu_parent,
translation=Gf.Vec3d(0, 0, 0),
orientation=Gf.Quatd(1, 0, 0, 0),
visualize=False,
)
return
def create_depth_camera(self, robot_prim_path):
self.depth_left_camera_path = f"{robot_prim_path}/zed2i_right_camera_isaac_frame/left_cam"
self.depth_right_camera_path = f"{robot_prim_path}/zed2i_right_camera_isaac_frame/right_cam"
self.left_camera = prims.create_prim(
prim_path=self.depth_left_camera_path,
prim_type="Camera",
attributes={
"focusDistance": 1,
"focalLength": 24,
"horizontalAperture": 20.955,
"verticalAperture": 15.2908,
"clippingRange": (0.1, 1000000),
"clippingPlanes": np.array([1.0, 0.0, 1.0, 1.0]),
},
)
self.right_camera = prims.create_prim(
prim_path=self.depth_right_camera_path,
prim_type="Camera",
attributes={
"focusDistance": 1,
"focalLength": 24,
"horizontalAperture": 20.955,
"verticalAperture": 15.2908,
"clippingRange": (0.1, 1000000),
"clippingPlanes": np.array([1.0, 0.0, 1.0, 1.0]),
},
)
return
def setup_world_action_graph(self):
og.Controller.edit(
{"graph_path": "/globalclock", "evaluator_name": "execution"},
{
og.Controller.Keys.CREATE_NODES: [
("OnPlaybackTick", "omni.graph.action.OnPlaybackTick"),
("ReadSimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"),
("Context", "omni.isaac.ros2_bridge.ROS2Context"),
("PublishClock", "omni.isaac.ros2_bridge.ROS2PublishClock"),
],
og.Controller.Keys.CONNECT: [
("OnPlaybackTick.outputs:tick", "PublishClock.inputs:execIn"),
("Context.outputs:context", "PublishClock.inputs:context"),
("ReadSimTime.outputs:simulationTime", "PublishClock.inputs:timeStamp"),
],
}
)
return
def setup_camera_action_graph(self, robot_prim_path):
camera_graph = "{}/camera_sensor_graph".format(robot_prim_path)
enable_left_cam = False
enable_right_cam = False
rgbType = "RgbType"
infoType = "InfoType"
depthType = "DepthType"
depthPclType = "DepthPclType"
def createCamType(side, name, typeNode, topic):
return {
"create": [
(f"{side}CamHelper{name}", "omni.isaac.ros2_bridge.ROS2CameraHelper"),
],
"connect": [
(f"{side}CamViewProduct.outputs:renderProductPath", f"{side}CamHelper{name}.inputs:renderProductPath"),
(f"{side}CamSet.outputs:execOut", f"{side}CamHelper{name}.inputs:execIn"),
(f"{typeNode}.inputs:value", f"{side}CamHelper{name}.inputs:type"),
],
"setvalues": [
(f"{side}CamHelper{name}.inputs:topicName", f"{side.lower()}/{topic}"),
(f"{side}CamHelper{name}.inputs:frameId", f"{NAMESPACE}/zed2i_{side.lower()}_camera_frame"),
(f"{side}CamHelper{name}.inputs:nodeNamespace", f"/{NAMESPACE}"),
]
}
def getCamNodes(side, enable):
camNodes = {
"create": [
(f"{side}CamBranch", "omni.graph.action.Branch"),
(f"{side}CamCreateViewport", "omni.isaac.core_nodes.IsaacCreateViewport"),
(f"{side}CamViewportResolution", "omni.isaac.core_nodes.IsaacSetViewportResolution"),
(f"{side}CamViewProduct", "omni.isaac.core_nodes.IsaacGetViewportRenderProduct"),
(f"{side}CamSet", "omni.isaac.core_nodes.IsaacSetCameraOnRenderProduct"),
],
"connect": [
("OnPlaybackTick.outputs:tick", f"{side}CamBranch.inputs:execIn"),
(f"{side}CamBranch.outputs:execTrue", f"{side}CamCreateViewport.inputs:execIn"),
(f"{side}CamCreateViewport.outputs:execOut", f"{side}CamViewportResolution.inputs:execIn"),
(f"{side}CamCreateViewport.outputs:viewport", f"{side}CamViewportResolution.inputs:viewport"),
(f"{side}CamCreateViewport.outputs:viewport", f"{side}CamViewProduct.inputs:viewport"),
(f"{side}CamViewportResolution.outputs:execOut", f"{side}CamViewProduct.inputs:execIn"),
(f"{side}CamViewProduct.outputs:execOut", f"{side}CamSet.inputs:execIn"),
(f"{side}CamViewProduct.outputs:renderProductPath", f"{side}CamSet.inputs:renderProductPath"),
],
"setvalues": [
(f"{side}CamBranch.inputs:condition", enable),
(f"{side}CamCreateViewport.inputs:name", f"{side}Cam"),
(f"{side}CamViewportResolution.inputs:width", 640),
(f"{side}CamViewportResolution.inputs:height", 360),
]
}
rgbNodes = createCamType(side, "RGB", rgbType, "rgb")
infoNodes = createCamType(side, "Info", infoType, "camera_info")
depthNodes = createCamType(side, "Depth", depthType, "depth")
depthPClNodes = createCamType(side, "DepthPcl", depthPclType, "depth_pcl")
camNodes["create"] += rgbNodes["create"] + infoNodes["create"] + depthNodes["create"] + depthPClNodes["create"]
camNodes["connect"] += rgbNodes["connect"] + infoNodes["connect"] + depthNodes["connect"] + depthPClNodes["connect"]
camNodes["setvalues"] += rgbNodes["setvalues"] + infoNodes["setvalues"] + depthNodes["setvalues"] + depthPClNodes["setvalues"]
return camNodes
leftCamNodes = getCamNodes("Left", enable_left_cam)
rightCamNodes = getCamNodes("Right", enable_right_cam)
og.Controller.edit(
{"graph_path": camera_graph, "evaluator_name": "execution"},
{
og.Controller.Keys.CREATE_NODES: [
("OnPlaybackTick", "omni.graph.action.OnPlaybackTick"),
(rgbType, "omni.graph.nodes.ConstantToken"),
(infoType, "omni.graph.nodes.ConstantToken"),
(depthType, "omni.graph.nodes.ConstantToken"),
(depthPclType, "omni.graph.nodes.ConstantToken"),
] + leftCamNodes["create"] + rightCamNodes["create"],
og.Controller.Keys.CONNECT: leftCamNodes["connect"] + rightCamNodes["connect"],
og.Controller.Keys.SET_VALUES: [
(f"{rgbType}.inputs:value", "rgb"),
(f"{infoType}.inputs:value", "camera_info"),
(f"{depthType}.inputs:value", "depth"),
(f"{depthPclType}.inputs:value", "depth_pcl"),
] + leftCamNodes["setvalues"] + rightCamNodes["setvalues"],
}
)
set_target_prims(primPath=f"{camera_graph}/RightCamSet", targetPrimPaths=[self.depth_right_camera_path], inputName="inputs:cameraPrim")
set_target_prims(primPath=f"{camera_graph}/LeftCamSet", targetPrimPaths=[self.depth_left_camera_path], inputName="inputs:cameraPrim")
return
def setup_imu_action_graph(self, robot_prim_path):
sensor_graph = "{}/imu_sensor_graph".format(robot_prim_path)
swerve_link = "{}/swerve_chassis_link".format(robot_prim_path)
lidar_link = "{}/lidar_link/lidar".format(robot_prim_path)
og.Controller.edit(
{"graph_path": sensor_graph, "evaluator_name": "execution"},
{
og.Controller.Keys.CREATE_NODES: [
# General Nodes
("OnPlaybackTick", "omni.graph.action.OnPlaybackTick"),
("SimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"),
("Context", "omni.isaac.ros2_bridge.ROS2Context"),
# Odometry Nodes
("ComputeOdometry", "omni.isaac.core_nodes.IsaacComputeOdometry"),
("PublishOdometry", "omni.isaac.ros2_bridge.ROS2PublishOdometry"),
("RawOdomTransform", "omni.isaac.ros2_bridge.ROS2PublishRawTransformTree"),
# LiDAR Nodes
# ("ReadLidar", "omni.isaac.range_sensor.IsaacReadLidarBeams"),
# ("PublishLidar", "omni.isaac.ros2_bridge.ROS2PublishLaserScan"),
# IMU Nodes
("IsaacReadImu", "omni.isaac.sensor.IsaacReadIMU"),
("PublishImu", "omni.isaac.ros2_bridge.ROS2PublishImu"),
],
og.Controller.Keys.SET_VALUES: [
("PublishOdometry.inputs:nodeNamespace", f"/{NAMESPACE}"),
# ("PublishLidar.inputs:nodeNamespace", f"/{NAMESPACE}"),
("PublishImu.inputs:nodeNamespace", f"/{NAMESPACE}"),
# ("PublishLidar.inputs:frameId", f"{NAMESPACE}/lidar_link"),
("RawOdomTransform.inputs:childFrameId", f"{NAMESPACE}/base_link"),
("RawOdomTransform.inputs:parentFrameId", f"{NAMESPACE}/zed/odom"),
("PublishOdometry.inputs:chassisFrameId", f"{NAMESPACE}/base_link"),
("PublishOdometry.inputs:odomFrameId", f"{NAMESPACE}/odom"),
("PublishImu.inputs:frameId", f"{NAMESPACE}/zed2i_imu_link"),
("PublishOdometry.inputs:topicName", "zed/odom")
],
og.Controller.Keys.CONNECT: [
# Odometry Connections
("OnPlaybackTick.outputs:tick", "ComputeOdometry.inputs:execIn"),
("OnPlaybackTick.outputs:tick", "RawOdomTransform.inputs:execIn"),
("ComputeOdometry.outputs:execOut", "PublishOdometry.inputs:execIn"),
("ComputeOdometry.outputs:angularVelocity", "PublishOdometry.inputs:angularVelocity"),
("ComputeOdometry.outputs:linearVelocity", "PublishOdometry.inputs:linearVelocity"),
("ComputeOdometry.outputs:orientation", "PublishOdometry.inputs:orientation"),
("ComputeOdometry.outputs:orientation", "RawOdomTransform.inputs:rotation"),
("ComputeOdometry.outputs:position", "PublishOdometry.inputs:position"),
("ComputeOdometry.outputs:position", "RawOdomTransform.inputs:translation"),
("Context.outputs:context", "PublishOdometry.inputs:context"),
("Context.outputs:context", "RawOdomTransform.inputs:context"),
("SimTime.outputs:simulationTime", "PublishOdometry.inputs:timeStamp"),
("SimTime.outputs:simulationTime", "RawOdomTransform.inputs:timeStamp"),
# LiDAR Connections
# ("OnPlaybackTick.outputs:tick", "ReadLidar.inputs:execIn"),
# ("ReadLidar.outputs:execOut", "PublishLidar.inputs:execIn"),
# ("Context.outputs:context", "PublishLidar.inputs:context"),
# ("SimTime.outputs:simulationTime", "PublishLidar.inputs:timeStamp"),
# ("ReadLidar.outputs:azimuthRange", "PublishLidar.inputs:azimuthRange"),
# ("ReadLidar.outputs:depthRange", "PublishLidar.inputs:depthRange"),
# ("ReadLidar.outputs:horizontalFov", "PublishLidar.inputs:horizontalFov"),
# ("ReadLidar.outputs:horizontalResolution", "PublishLidar.inputs:horizontalResolution"),
# ("ReadLidar.outputs:intensitiesData", "PublishLidar.inputs:intensitiesData"),
# ("ReadLidar.outputs:linearDepthData", "PublishLidar.inputs:linearDepthData"),
# ("ReadLidar.outputs:numCols", "PublishLidar.inputs:numCols"),
# ("ReadLidar.outputs:numRows", "PublishLidar.inputs:numRows"),
# ("ReadLidar.outputs:rotationRate", "PublishLidar.inputs:rotationRate"),
# IMU Connections
("OnPlaybackTick.outputs:tick", "IsaacReadImu.inputs:execIn"),
("IsaacReadImu.outputs:execOut", "PublishImu.inputs:execIn"),
("Context.outputs:context", "PublishImu.inputs:context"),
("SimTime.outputs:simulationTime", "PublishImu.inputs:timeStamp"),
("IsaacReadImu.outputs:angVel", "PublishImu.inputs:angularVelocity"),
("IsaacReadImu.outputs:linAcc", "PublishImu.inputs:linearAcceleration"),
("IsaacReadImu.outputs:orientation", "PublishImu.inputs:orientation"),
],
}
)
# Setup target prims for the Odometry and the Lidar
set_target_prims(primPath=f"{sensor_graph}/ComputeOdometry", targetPrimPaths=[swerve_link], inputName="inputs:chassisPrim")
set_target_prims(primPath=f"{sensor_graph}/ComputeOdometry", targetPrimPaths=[swerve_link], inputName="inputs:chassisPrim")
set_target_prims(primPath=f"{sensor_graph}/IsaacReadImu", targetPrimPaths=[self.imu_prim_path], inputName="inputs:imuPrim")
return
def setup_robot_action_graph(self, robot_prim_path):
robot_controller_path = f"{robot_prim_path}/ros_interface_controller"
og.Controller.edit(
{"graph_path": robot_controller_path, "evaluator_name": "execution"},
{
og.Controller.Keys.CREATE_NODES: [
("OnPlaybackTick", "omni.graph.action.OnPlaybackTick"),
("ReadSimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"),
("Context", "omni.isaac.ros2_bridge.ROS2Context"),
("PublishJointState", "omni.isaac.ros2_bridge.ROS2PublishJointState"),
("SubscribeJointState", "omni.isaac.ros2_bridge.ROS2SubscribeJointState"),
("articulation_controller", "omni.isaac.core_nodes.IsaacArticulationController"),
],
og.Controller.Keys.SET_VALUES: [
("PublishJointState.inputs:topicName", "isaac_joint_states"),
("SubscribeJointState.inputs:topicName", "isaac_joint_commands"),
("articulation_controller.inputs:usePath", False),
("SubscribeJointState.inputs:nodeNamespace", f"/{NAMESPACE}"),
("PublishJointState.inputs:nodeNamespace", f"/{NAMESPACE}"),
],
og.Controller.Keys.CONNECT: [
("OnPlaybackTick.outputs:tick", "PublishJointState.inputs:execIn"),
("OnPlaybackTick.outputs:tick", "SubscribeJointState.inputs:execIn"),
("OnPlaybackTick.outputs:tick", "articulation_controller.inputs:execIn"),
("ReadSimTime.outputs:simulationTime", "PublishJointState.inputs:timeStamp"),
("Context.outputs:context", "PublishJointState.inputs:context"),
("Context.outputs:context", "SubscribeJointState.inputs:context"),
("SubscribeJointState.outputs:jointNames", "articulation_controller.inputs:jointNames"),
("SubscribeJointState.outputs:velocityCommand", "articulation_controller.inputs:velocityCommand"),
("SubscribeJointState.outputs:positionCommand", "articulation_controller.inputs:positionCommand"),
],
}
)
set_target_prims(primPath=f"{robot_controller_path}/articulation_controller", targetPrimPaths=[robot_prim_path])
set_target_prims(primPath=f"{robot_controller_path}/PublishJointState", targetPrimPaths=[robot_prim_path])
return
async def setup_pre_reset(self):
return
async def setup_post_reset(self):
return
async def setup_post_clear(self):
return
def world_cleanup(self):
carb.log_info(f"Removing {self.robot_name}")
if self._world is not None:
self._world.scene.remove_object(self.robot_name)
return
| 29,278 | Python | 54.663498 | 164 | 0.609092 |
RoboEagles4828/offseason2023/isaac/Swervesim/rlgpu_conda_env.yml | name: rlgpu
channels:
- pytorch
- conda-forge
- defaults
dependencies:
- python=3.8
- pytorch=1.8.1
- torchvision=0.9.1
- cudatoolkit=11.1
- pyyaml>=5.3.1
- scipy>=1.5.0
- tensorboard==2.9.0
- tensorboard-plugin-wit==1.8.1
- protobuf==3.9.2
| 268 | YAML | 14.823529 | 34 | 0.615672 |
RoboEagles4828/offseason2023/isaac/Swervesim/swervesim/tasks/swerve_field.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.tasks.base.rl_task import RLTask
from swervesim.robots.articulations.swerve import Swerve
from swervesim.robots.articulations.views.swerve_view import SwerveView
from swervesim.tasks.utils.usd_utils import set_drive
from omni.isaac.core.objects import DynamicSphere
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.torch.rotations import *
from omni.isaac.core.prims import RigidPrimView, GeometryPrim
from omni.isaac.core.utils.stage import add_reference_to_stage
import numpy as np
import torch
import math
class Swerve_Field_Task(RLTask):
def __init__(
self,
name,
sim_config,
env,
offset=None
) -> None:
# sets up the sim
self._sim_config = sim_config
self._cfg = sim_config.config
self._task_cfg = sim_config.task_config
# limits max velocity of wheels and axles
self.velocity_limit = 10
self.dt = 1 / 60
self.max_episode_length_s = self._task_cfg["env"]["episodeLength_s"]
self._max_episode_length = int(
self.max_episode_length_s / self.dt + 0.5)
self.Kp = self._task_cfg["env"]["control"]["stiffness"]
self.Kd = self._task_cfg["env"]["control"]["damping"]
# for key in self.rew_scales.keys():
# self.rew_scales[key] *= self.dt
self._num_envs = self._task_cfg["env"]["numEnvs"]
self._swerve_translation = torch.tensor([0.0, 0.0, 0.0])
self._env_spacing = self._task_cfg["env"]["envSpacing"]
# Number of data points the policy is recieving
self._num_observations = 29
# Number of data points the policy is producing
self._num_actions = 8
# starting position of the swerve module
self.swerve_position = torch.tensor([0, 0, 0])
# starting position of the target
self._ball_position = torch.tensor([1, 1, 0])
self.swerve_initia_pos = []
RLTask.__init__(self, name, env)
self.target_positions = torch.zeros(
(self._num_envs, 3), device=self._device, dtype=torch.float32) # xyx of target position
self.target_positions[:, 1] = 1
return
# Adds all of the items to the stage
def set_up_scene(self, scene) -> None:
# Adds USD of swerve to stage
self.get_swerve()
# Adds ball to stage
self.get_target()
super().set_up_scene(scene)
# Sets up articluation controller for swerve
self._swerve = SwerveView(
prim_paths_expr="/World/envs/.*/swerve", name="swerveview")
# Allows for position tracking of targets
# self._balls = RigidPrimView(
# prim_paths_expr="/World/envs/.*/ball", name="targets_view", reset_xform_properties=False)
# Adds everything to the scene
scene.add(self._swerve)
for axle in self._swerve._axle:
scene.add(axle)
for wheel in self._swerve._wheel:
scene.add(wheel)
scene.add(self._swerve._base)
# scene.add(self._balls)
# print("scene set up")
return
def get_swerve(self):
# Adds swerve to env_0 and adds articulation controller
swerve = Swerve(self.default_zero_env_path + "/swerve",
"swerve", self._swerve_translation)
self._sim_config.apply_articulation_settings("swerve", get_prim_at_path(
swerve.prim_path), self._sim_config.parse_actor_config("swerve"))
# def get_target(self):
# # Adds a red ball as target
# radius = 0.1 # meters
# color = torch.tensor([0, 0, 1])
# ball = DynamicSphere(
# prim_path=self.default_zero_env_path + "/ball",
# translation=self._ball_position,
# name="target_0",
# radius=radius,
# color=color,
# )
# self._sim_config.apply_articulation_settings("ball", get_prim_at_path(
# ball.prim_path), self._sim_config.parse_actor_config("ball"))
# ball.set_collision_enabled(False)
def get_target(self):
# world = self.get_world()
self.task_path = os.path.abspath(__file__)
self.project_root_path = os.path.abspath(os.path.join(self.task_path, "../../../../../../../.."))
field = os.path.join(self.project_root_path, "isaac/assets/2023_field/FE-2023.usd")
add_reference_to_stage(usd_path=field,prim_path=self.default_zero_env_path+"/Field")
cone = os.path.join(self.project_root_path, "isaac/assets/2023_field/parts/cone_without_deformable_body.usd")
cube = os.path.join(self.project_root_path, "isaac/assets/2023_field/parts/cube_without_deformable_body.usd")
chargestation = os.path.join(self.project_root_path, "isaac/assets/Charge Station/Assembly-1.usd")
add_reference_to_stage(chargestation, self.default_zero_env_path+"/ChargeStation_1")
add_reference_to_stage(chargestation, self.default_zero_env_path+"/ChargeStation_2")
add_reference_to_stage(cone, self.default_zero_env_path+"/Cone_1")
add_reference_to_stage(cone, self.default_zero_env_path+"/Cone_2")
add_reference_to_stage(cone, self.default_zero_env_path+"/Cone_3")
add_reference_to_stage(cone, self.default_zero_env_path+"/Cone_4")
# add_reference_to_stage(cone, self.default_zero_env_path+"/Cone_5")
# add_reference_to_stage(cone, self.default_zero_env_path+"/Cone_6")
# add_reference_to_stage(cone, self.default_zero_env_path+"/Cone_7")
# add_reference_to_stage(cone, self.default_zero_env_path+"/Cone_8")
self.cone_1 = GeometryPrim(self.default_zero_env_path+"/Cone_1","cone_1_view",position=np.array([1.20298,-0.56861,0.0]))
self.cone_2 = GeometryPrim(self.default_zero_env_path+"/Cone_2","cone_2_view",position=np.array([1.20298,3.08899,0.0]))
self.cone_3 = GeometryPrim(self.default_zero_env_path+"/Cone_3","cone_3_view",position=np.array([-1.20298,-0.56861,0.0]))
self.cone_4 = GeometryPrim(self.default_zero_env_path+"/Cone_4","cone_4_view",position=np.array([-1.20298,3.08899,0.0]))
chargestation_1 = GeometryPrim(self.default_zero_env_path+"/ChargeStation_1","cone_3_view",position=np.array([-4.20298,-0.56861,0.0]))
chargestation_2 = GeometryPrim(self.default_zero_env_path+"/ChargeStation_2","cone_4_view",position=np.array([4.20298,0.56861,0.0]))
add_reference_to_stage(cube, self.default_zero_env_path+"/Cube_1")
add_reference_to_stage(cube, self.default_zero_env_path+"/Cube_2")
add_reference_to_stage(cube, self.default_zero_env_path+"/Cube_3")
add_reference_to_stage(cube, self.default_zero_env_path+"/Cube_4")
# add_reference_to_stage(cube, self.default_zero_env_path+"/Cube_5")
# add_reference_to_stage(cube, self.default_zero_env_path+"/Cube_6")
# add_reference_to_stage(cube, self.default_zero_env_path+"/Cube_7")
# add_reference_to_stage(cube, self.default_zero_env_path+"/Cube_8")
self.cube_1 = GeometryPrim(self.default_zero_env_path+"/Cube_1","cube_1_view",position=np.array([1.20298,0.65059,0.121]))
self.cube_2 = GeometryPrim(self.default_zero_env_path+"/Cube_2","cube_2_view",position=np.array([1.20298,1.86979,0.121]))
self.cube_3 = GeometryPrim(self.default_zero_env_path+"/Cube_3","cube_3_view",position=np.array([-1.20298,0.65059,0.121]))
self.cube_4 = GeometryPrim(self.default_zero_env_path+"/Cube_4","cube_4_view",position=np.array([-1.20298,1.86979,0.121]))
return
def get_observations(self) -> dict:
# Gets various positions and velocties to observations
self.root_pos, self.root_rot = self._swerve.get_world_poses(
clone=False)
self.joint_velocities = self._swerve.get_joint_velocities()
self.joint_positions = self._swerve.get_joint_positions()
self.root_velocities = self._swerve.get_velocities(clone=False)
root_positions = self.root_pos - self._env_pos
root_quats = self.root_rot
# root_linvels = self.root_velocities[:, :3]
# root_angvels = self.root_velocities[:, 3:]
self.obs_buf[..., 0:3] = (self.target_positions - root_positions) / 3
self.obs_buf[..., 3:6] = (self.target_positions - root_positions) / 3
self.obs_buf[..., 6:9] = (self.target_positions - root_positions) / 3
self.obs_buf[..., 9:13] = root_quats
self.obs_buf[..., 13:21] = self.joint_velocities
self.obs_buf[..., 21:29] = self.joint_positions
# Should not exceed observation ssize declared earlier
# An observation is created for each swerve in each environment
observations = {
self._swerve.name: {
"obs_buf": self.obs_buf
}
}
return observations
def pre_physics_step(self, actions) -> None:
# This is what sets the action for swerve
reset_env_ids = self.reset_buf.nonzero(as_tuple=False).squeeze(-1)
if len(reset_env_ids) > 0:
self.reset_idx(reset_env_ids)
set_target_ids = (self.progress_buf % 500 == 0).nonzero(
as_tuple=False).squeeze(-1)
if len(set_target_ids) > 0:
self.set_targets(set_target_ids)
self.actions[:] = actions.clone().to(self._device)
# Sets velocity for each wheel and axle within the velocity limits
linear_x_cmd = torch.clamp(
actions[:, 0:1] * self.velocity_limit, -self.velocity_limit, self.velocity_limit)
linear_y_cmd = torch.clamp(
actions[:, 1:2] * self.velocity_limit, -self.velocity_limit, self.velocity_limit)
angular_cmd = torch.clamp(
actions[:, 2:3] * self.velocity_limit, -self.velocity_limit, self.velocity_limit)
x_offset = 0.7366
radius = 0.1016
actionlist = []
for i in range(self.num_envs):
action = []
# Compute Wheel Velocities and Positions
a = linear_x_cmd[i] - angular_cmd[i] * x_offset / 2
b = linear_x_cmd[i] + angular_cmd[i] * x_offset / 2
c = linear_y_cmd[i] - angular_cmd[i] * x_offset / 2
d = linear_y_cmd[i] + angular_cmd[i] * x_offset / 2
# get current wheel positions
front_left_current_pos = (
(self._swerve.get_joint_positions()[i][0]))
front_right_current_pos = (
(self._swerve.get_joint_positions()[i][1]))
rear_left_current_pos = (
(self._swerve.get_joint_positions()[i][2]))
rear_right_current_pos = (
(self._swerve.get_joint_positions()[i][3]))
front_left_velocity = (
math.sqrt(math.pow(b, 2) + math.pow(d, 2)))*(1/(radius*math.pi))
front_right_velocity = (
math.sqrt(math.pow(b, 2) + math.pow(c, 2)))*(1/(radius*math.pi))
rear_left_velocity = (
math.sqrt(math.pow(a, 2) + math.pow(d, 2)))*(1/(radius*math.pi))
rear_right_velocity = (
math.sqrt(math.pow(a, 2) + math.pow(c, 2)))*(1/(radius*math.pi))
front_left_position = math.atan2(b, d)
front_right_position = math.atan2(b, c)
rear_left_position = math.atan2(a, d)
rear_right_position = math.atan2(a, c)
# optimization
front_left_position, front_left_velocity = simplifiy_angle(
front_left_current_pos, front_left_position, front_left_velocity)
front_right_position, front_right_velocity = simplifiy_angle(
front_right_current_pos, front_right_position, front_right_velocity)
rear_left_position, rear_left_velocity = simplifiy_angle(
rear_left_current_pos, rear_left_position, rear_left_velocity)
rear_right_position, rear_right_velocity = simplifiy_angle(
rear_right_current_pos, rear_right_position, rear_right_velocity)
# Set Wheel Positions
# Has a 1 degree tolerance. Turns clockwise if less than, counter clockwise if greater than
if (i == 1):
print(f"front_left_position:{front_left_position}")
print(f"rear_left_position:{rear_left_position}")
action.append(calculate_turn_velocity(front_left_current_pos, front_left_position))
action.append(calculate_turn_velocity(front_right_current_pos, front_right_position))
action.append(calculate_turn_velocity(rear_left_current_pos, rear_left_position))
action.append(calculate_turn_velocity(rear_right_current_pos, rear_right_position))
sortlist=[front_left_velocity, front_right_velocity, rear_left_velocity, rear_right_velocity]
maxs = abs(max(sortlist, key=abs))
if (maxs < 0.5):
for num in sortlist:
action.append(0.0)
else:
for num in sortlist:
if (maxs != 0 and abs(maxs) > 10):
# scales down velocty to max of 10 radians
num = (num/abs(maxs))*10
# print(num)
action.append(num)
# print(len(action))
actionlist.append(action)
# Sets robots velocities
self._swerve.set_joint_velocities(torch.FloatTensor(actionlist))
def reset_idx(self, env_ids):
# print("line 211")
# For when the environment resets. This is great for randomization and increases the chances of a successful policy in the real world
num_resets = len(env_ids)
# Turns the wheels and axles -pi to pi radians
self.dof_pos[env_ids, 1] = torch_rand_float(
-math.pi, math.pi, (num_resets, 1), device=self._device).squeeze()
self.dof_pos[env_ids, 3] = torch_rand_float(
-math.pi, math.pi, (num_resets, 1), device=self._device).squeeze()
self.dof_vel[env_ids, :] = 0
root_pos = self.initial_root_pos.clone()
root_pos[env_ids, 0] += torch_rand_float(-0.5, 0.5,
(num_resets, 1), device=self._device).view(-1)
root_pos[env_ids, 1] += torch_rand_float(-0.5, 0.5,
(num_resets, 1), device=self._device).view(-1)
root_pos[env_ids, 2] += torch_rand_float(
0, 0, (num_resets, 1), device=self._device).view(-1)
root_velocities = self.root_velocities.clone()
root_velocities[env_ids] = 0
# apply resets
self._swerve.set_joint_positions(
self.dof_pos[env_ids], indices=env_ids)
self._swerve.set_joint_velocities(
self.dof_vel[env_ids], indices=env_ids)
self._swerve.set_world_poses(
root_pos[env_ids], self.initial_root_rot[env_ids].clone(), indices=env_ids)
self._swerve.set_velocities(root_velocities[env_ids], indices=env_ids)
# bookkeeping
self.reset_buf[env_ids] = 0
self.progress_buf[env_ids] = 0
# print("line 249")
def post_reset(self):
# print("line 252")
self.root_pos, self.root_rot = self._swerve.get_world_poses()
self.root_velocities = self._swerve.get_velocities()
self.dof_pos = self._swerve.get_joint_positions()
self.dof_vel = self._swerve.get_joint_velocities()
# self.initial_ball_pos, self.initial_ball_rot = self._balls.get_world_poses()
# self.initial_root_pos, self.initial_root_rot = self.root_pos.clone(), self.root_rot.clone()
# initialize some data used later on
self.extras = {}
self.actions = torch.zeros(
self._num_envs, self.num_actions, dtype=torch.float, device=self._device, requires_grad=False
)
self.last_dof_vel = torch.zeros(
(self._num_envs, 12), dtype=torch.float, device=self._device, requires_grad=False)
self.last_actions = torch.zeros(
self._num_envs, self.num_actions, dtype=torch.float, device=self._device, requires_grad=False)
self.time_out_buf = torch.zeros_like(self.reset_buf)
# randomize all envs
indices = torch.arange(
self._swerve.count, dtype=torch.int64, device=self._device)
self.reset_idx(indices)
def set_targets(self, env_ids):
num_sets = len(env_ids)
envs_long = env_ids.long()
# set target position randomly with x, y in (-20, 20)
self.target_positions[envs_long, 0:2] = torch.rand(
(num_sets, 2), device=self._device) * 20 - 1
self.target_positions[envs_long, 2] = 0.1
# print(self.target_positions)
# shift the target up so it visually aligns better
ball_pos = self.target_positions[envs_long] + self._env_pos[envs_long]
self._balls.set_world_poses(
ball_pos[:, 0:3], self.initial_ball_rot[envs_long].clone(), indices=env_ids)
def calculate_metrics(self) -> None:
root_positions = self.root_pos - self._env_pos
# distance to target
target_dist = torch.sqrt(torch.square(
self.target_positions - root_positions).sum(-1))
pos_reward = 1.0 / (1.0 + 2.5 * target_dist * target_dist)
self.target_dist = target_dist
self.root_positions = root_positions
self.root_position_reward = self.rew_buf
# rewards for moving away form starting point
for i in range(len(self.root_position_reward)):
self.root_position_reward[i] = sum(root_positions[i][0:3])
self.rew_buf[:] = self.root_position_reward*pos_reward
def is_done(self) -> None:
# print("line 312")
# These are the dying constaints. It dies if it is going in the wrong direction or starts flying
ones = torch.ones_like(self.reset_buf)
die = torch.zeros_like(self.reset_buf)
die = torch.where(self.target_dist > 20.0, ones, die)
die = torch.where(self.root_positions[..., 2] > 0.5, ones, die)
# resets due to episode length
self.reset_buf[:] = torch.where(
self.progress_buf >= self._max_episode_length - 1, ones, die)
# print("line 316")
def simplifiy_angle(current_pos, turn_pos, velocity):
while (abs(current_pos - turn_pos) > math.pi / 2):
if(turn_pos>current_pos):
turn_pos -= math.pi
else:
turn_pos += math.pi
velocity *= -1
return turn_pos, velocity
def calculate_turn_velocity(current_pos, turn_position):
turningspeed = 5.0
setspeed = 0.0
if (current_pos > turn_position+(math.pi/90) or current_pos < turn_position-(math.pi/90)):
setspeed = abs(turn_position-current_pos)/(math.pi/9)
if (setspeed > turningspeed):
setspeed = turningspeed
if (turn_position < current_pos):
setspeed *= -1
return setspeed
| 20,572 | Python | 46.18578 | 142 | 0.615545 |
RoboEagles4828/offseason2023/isaac/Swervesim/swervesim/tasks/swerve_charge_station.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.tasks.base.rl_task import RLTask
from swervesim.robots.articulations.swerve import Swerve
from swervesim.robots.articulations.views.swerve_view import SwerveView
from swervesim.robots.articulations.views.charge_station_view import ChargeStationView
from swervesim.tasks.utils.usd_utils import set_drive
from omni.isaac.core.objects import DynamicSphere
from omni.isaac.core.articulations import Articulation
from omni.isaac.core.utils.prims import get_prim_at_path
from omni.isaac.core.utils.torch.rotations import *
from omni.isaac.core.prims import RigidPrimView
from omni.isaac.core.utils.stage import add_reference_to_stage
import numpy as np
import torch
import math
from shapely.geometry import Polygon
class Swerve_Charge_Station_Task(RLTask):
def __init__(
self,
name,
sim_config,
env,
offset=None
) -> None:
# sets up the sim
self._sim_config = sim_config
self._cfg = sim_config.config
self._task_cfg = sim_config.task_config
# limits max velocity of wheels and axles
self.velocity_limit = 10*math.pi
self.dt = 1 / 10
self.dt_total = 0.0
self.max_episode_length_s = self._task_cfg["env"]["episodeLength_s"]
self._max_episode_length = int(
self.max_episode_length_s / self.dt)
self.Kp = self._task_cfg["env"]["control"]["stiffness"]
self.Kd = self._task_cfg["env"]["control"]["damping"]
# for key in self.rew_scales.keys():
# self.rew_scales[key] *= self.dt
self._num_envs = self._task_cfg["env"]["numEnvs"]
self._swerve_translation = torch.tensor([0.0, 0.0, 0.0])
self._env_spacing = self._task_cfg["env"]["envSpacing"]
# Number of data points the policy is recieving
self._num_observations = 37
# Number of data points the policy is producing
self._num_actions = 8
# starting position of the swerve module
self.swerve_position = torch.tensor([0, 0, 0])
# starting position of the target
self._chargestation_part_1_position = torch.tensor([1, 1, 0])
self.swerve_initia_pos = []
RLTask.__init__(self, name, env)
self.target_positions = torch.zeros(
(self._num_envs, 3), device=self._device, dtype=torch.float32) # xyx of target position
self.target_rotation = torch.zeros(
(self._num_envs, 4), device=self._device, dtype=torch.float32) #ypr
self.target_positions[:, 1] = 1
return
# Adds all of the items to the stage
def set_up_scene(self, scene) -> None:
# Adds USD of swerve to stage
self.get_swerve()
# Adds ball to stage
self.get_charge_station()
super().set_up_scene(scene)
# Sets up articluation controller for swerve
self._swerve = SwerveView(
prim_paths_expr="/World/envs/.*/swerve", name="swerveview")
self._charge_station= ChargeStationView(prim_paths_expr="/World/envs/.*/ChargeStation", name="ChargeStation_1_view")
# Allows for position tracking of targets
# Adds everything to the scene
scene.add(self._swerve)
for axle in self._swerve._axle:
scene.add(axle)
for wheel in self._swerve._wheel:
scene.add(wheel)
scene.add(self._swerve._base)
scene.add(self._charge_station)
# print("scene set up")
return
def get_swerve(self):
# Adds swerve to env_0 and adds articulation controller
swerve = Swerve(self.default_zero_env_path + "/swerve",
"swerve", self._swerve_translation)
self._sim_config.apply_articulation_settings("swerve", get_prim_at_path(
swerve.prim_path), self._sim_config.parse_actor_config("swerve"))
def get_charge_station(self):
chargestation = "/root/edna/isaac/assets/ChargeStation-Copy/Assembly-1.usd"
add_reference_to_stage(chargestation, self.default_zero_env_path+"/ChargeStation")
charge_station_1 = Articulation(prim_path=self.default_zero_env_path+"/ChargeStation",name="ChargeStation")
self._sim_config.apply_articulation_settings("ChargeStation", get_prim_at_path(
charge_station_1.prim_path), self._sim_config.parse_actor_config("ChargeStation"))
def get_observations(self) -> dict:
# Gets various positions and velocties to observations
self.root_pos, self.root_rot = self._swerve.get_world_poses(clone=False)
self.joint_velocities = self._swerve.get_joint_velocities()
self.joint_positions = self._swerve.get_joint_positions()
self.charge_station_pos, self.charge_station_rot = self._charge_station.get_world_poses(clone=False)
self.chargestation_vertices = torch.zeros(
(self._num_envs, 8), device=self._device, dtype=torch.float32) #ypr
charge_station_pos = self.charge_station_pos - self._env_pos
for i in range(len(self.charge_station_pos)):
w=self.charge_station_rot[i][0]
x=self.charge_station_rot[i][1]
y=self.charge_station_rot[i][2]
z=self.charge_station_rot[i][3]
# print(f"x:{x} y:{y} z:{z} w:{w}")
siny_cosp = 2 * (w * z + x * y)
cosy_cosp = 1 - 2 * (y * y + z * z)
angle = math.atan2(siny_cosp, cosy_cosp)
self.chargestation_vertices[i][0] , self.chargestation_vertices[i][1] = findB(charge_station_pos[i][0],charge_station_pos[i][1],math.pi-angle)
self.chargestation_vertices[i][2] , self.chargestation_vertices[i][3] = findB(charge_station_pos[i][0],charge_station_pos[i][1],angle)
self.chargestation_vertices[i][4] , self.chargestation_vertices[i][5] = findB(charge_station_pos[i][0],charge_station_pos[i][1],(2*math.pi)-angle)
self.chargestation_vertices[i][6] , self.chargestation_vertices[i][7] = findB(charge_station_pos[i][0],charge_station_pos[i][1],angle+math.pi)
self.root_velocities = self._swerve.get_velocities(clone=False)
root_positions = self.root_pos - self._env_pos
root_quats = self.root_rot
root_linvels = self.root_velocities[:, :3]
root_angvels = self.root_velocities[:, 3:]
self.obs_buf[..., 0:3] = (root_positions) / 3
self.obs_buf[..., 3:7] = root_quats
self.obs_buf[..., 7:10] = root_linvels / 2
self.obs_buf[..., 10:13] = root_angvels / math.pi
self.obs_buf[..., 13:21] = self.joint_velocities
self.obs_buf[..., 21:29] = self.joint_positions
self.obs_buf[..., 29:37] = self.chargestation_vertices
# Should not exceed observation ssize declared earlier
# An observation is created for each swerve in each environment
observations = {
self._swerve.name: {
"obs_buf": self.obs_buf
}
}
return observations
def pre_physics_step(self, actions) -> None:
# This is what sets the action for swerve
reset_env_ids = self.reset_buf.nonzero(as_tuple=False).squeeze(-1)
if len(reset_env_ids) > 0:
self.reset_idx(reset_env_ids)
set_target_ids = (self.progress_buf % 500 == 0).nonzero(
as_tuple=False).squeeze(-1)
if len(set_target_ids) > 0:
self.set_targets(set_target_ids)
self.actions[:] = actions.clone().to(self._device)
# Sets velocity for each wheel and axle within the velocity limits
linear_x_cmd = torch.clamp(
actions[:, 0:1] * self.velocity_limit, -self.velocity_limit, self.velocity_limit)
linear_y_cmd = torch.clamp(
actions[:, 1:2] * self.velocity_limit, -self.velocity_limit, self.velocity_limit)
angular_cmd = torch.clamp(
actions[:, 2:3] * self.velocity_limit, -self.velocity_limit, self.velocity_limit)
x_offset = 0.7366
radius = 0.1016
actionlist = []
for i in range(self.num_envs):
action = []
# Compute Wheel Velocities and Positions
a = linear_x_cmd[i] - angular_cmd[i] * x_offset / 2
b = linear_x_cmd[i] + angular_cmd[i] * x_offset / 2
c = linear_y_cmd[i] - angular_cmd[i] * x_offset / 2
d = linear_y_cmd[i] + angular_cmd[i] * x_offset / 2
# get current wheel positions
front_left_current_pos = (
(self._swerve.get_joint_positions()[i][0]))
front_right_current_pos = (
(self._swerve.get_joint_positions()[i][1]))
rear_left_current_pos = (
(self._swerve.get_joint_positions()[i][2]))
rear_right_current_pos = (
(self._swerve.get_joint_positions()[i][3]))
front_left_velocity = (
math.sqrt(math.pow(b, 2) + math.pow(d, 2)))*(1/(radius*math.pi))
front_right_velocity = (
math.sqrt(math.pow(b, 2) + math.pow(c, 2)))*(1/(radius*math.pi))
rear_left_velocity = (
math.sqrt(math.pow(a, 2) + math.pow(d, 2)))*(1/(radius*math.pi))
rear_right_velocity = (
math.sqrt(math.pow(a, 2) + math.pow(c, 2)))*(1/(radius*math.pi))
front_left_position = math.atan2(b, d)
front_right_position = math.atan2(b, c)
rear_left_position = math.atan2(a, d)
rear_right_position = math.atan2(a, c)
# optimization
front_left_position, front_left_velocity = simplifiy_angle(
front_left_current_pos, front_left_position, front_left_velocity)
front_right_position, front_right_velocity = simplifiy_angle(
front_right_current_pos, front_right_position, front_right_velocity)
rear_left_position, rear_left_velocity = simplifiy_angle(
rear_left_current_pos, rear_left_position, rear_left_velocity)
rear_right_position, rear_right_velocity = simplifiy_angle(
rear_right_current_pos, rear_right_position, rear_right_velocity)
# Set Wheel Positions
# Has a 1 degree tolerance. Turns clockwise if less than, counter clockwise if greater than
# if (i == 1):
# print(f"front_left_position:{front_left_position}")
# print(f"rear_left_position:{rear_left_position}")
action.append(calculate_turn_velocity(front_left_current_pos, front_left_position))
action.append(calculate_turn_velocity(front_right_current_pos, front_right_position))
action.append(calculate_turn_velocity(rear_left_current_pos, rear_left_position))
action.append(calculate_turn_velocity(rear_right_current_pos, rear_right_position))
sortlist=[front_left_velocity, front_right_velocity, rear_left_velocity, rear_right_velocity]
maxs = abs(max(sortlist, key=abs))
if (maxs < 0.5):
for num in sortlist:
action.append(0.0)
else:
for num in sortlist:
if (maxs != 0 and abs(maxs) > 10):
# scales down velocty to max of 10 radians
num = (num/abs(maxs))*10
# print(num)
action.append(num)
# print(len(action))
actionlist.append(action)
# Sets robots velocities
self._swerve.set_joint_velocities(torch.FloatTensor(actionlist))
def reset_idx(self, env_ids):
# print("line 211")
# For when the environment resets. This is great for randomization and increases the chances of a successful policy in the real world
num_resets = len(env_ids)
# Turns the wheels and axles -pi to pi radians
self.dof_pos[env_ids, 1] = torch_rand_float(
-math.pi, math.pi, (num_resets, 1), device=self._device).squeeze()
self.dof_pos[env_ids, 3] = torch_rand_float(
-math.pi, math.pi, (num_resets, 1), device=self._device).squeeze()
self.dof_vel[env_ids, :] = 0
root_pos = self.initial_root_pos.clone()
root_pos[env_ids, 0] += torch_rand_float(-0.5, 0.5,
(num_resets, 1), device=self._device).view(-1)
root_pos[env_ids, 1] += torch_rand_float(-0.5, 0.5,
(num_resets, 1), device=self._device).view(-1)
root_pos[env_ids, 2] += torch_rand_float(
0, 0, (num_resets, 1), device=self._device).view(-1)
root_velocities = self.root_velocities.clone()
root_velocities[env_ids] = 0
# apply resets
self._swerve.set_joint_positions(
self.dof_pos[env_ids], indices=env_ids)
self._swerve.set_joint_velocities(
self.dof_vel[env_ids], indices=env_ids)
self._swerve.set_world_poses(
root_pos[env_ids], self.initial_root_rot[env_ids].clone(), indices=env_ids)
self._swerve.set_velocities(root_velocities[env_ids], indices=env_ids)
# bookkeeping
self.reset_buf[env_ids] = 0
self.progress_buf[env_ids] = 0
self.dt_total = 0
# print("line 249")
def post_reset(self):
# print("line 252")
self.root_pos, self.root_rot = self._swerve.get_world_poses()
self.root_velocities = self._swerve.get_velocities()
self.dof_pos = self._swerve.get_joint_positions()
self.dof_vel = self._swerve.get_joint_velocities()
self.initial_charge_station_pos, self.initial_charge_station_rot = self._charge_station.get_world_poses()
self.initial_root_pos, self.initial_root_rot = self.root_pos.clone(), self.root_rot.clone()
# initialize some data used later on
self.extras = {}
self.actions = torch.zeros(
self._num_envs, self.num_actions, dtype=torch.float, device=self._device, requires_grad=False
)
self.last_dof_vel = torch.zeros(
(self._num_envs, 12), dtype=torch.float, device=self._device, requires_grad=False)
self.last_actions = torch.zeros(
self._num_envs, self.num_actions, dtype=torch.float, device=self._device, requires_grad=False)
self.time_out_buf = torch.zeros_like(self.reset_buf)
# randomize all envs
indices = torch.arange(
self._swerve.count, dtype=torch.int64, device=self._device)
self.reset_idx(indices)
def set_targets(self, env_ids):
num_sets = len(env_ids)
envs_long = env_ids.long()
# set target position randomly with x, y in (-8, 8)
self.target_positions[envs_long, 0:2] = torch.rand(
(num_sets, 2), device=self._device) * 8 - 1
self.target_rotation[envs_long, 0]= 0
self.target_rotation[envs_long, 1]= torch.rand((num_sets), device=self._device)
# self.target_rotation = self.target_rotation[envs_long]+self.initial_charge_station_rot[envs_long]
self.target_rotation[envs_long, 2]= 1
self.target_rotation[envs_long, 3] = 0#
self.target_positions[envs_long,2] = 0
# print(self.target_positions)
# shift the target up so it visually aligns better
charge_station_pos = self.target_positions[envs_long] + self._env_pos[envs_long]
# print(self.initial_charge_station_rot)
# print(self.target_rotation)
self._charge_station.set_world_poses(
charge_station_pos[:, 0:3], self.target_rotation[envs_long].clone(), indices=env_ids)
def calculate_metrics(self) -> None:
self.dt_total += self.dt
root_positions = self.root_pos - self._env_pos
# distance to target
target_dist = torch.sqrt(torch.square(
self.target_positions - root_positions).sum(-1))
charge_station_score = in_charge_station(self.chargestation_vertices,self._swerve.get_axle_positions(), self._device)
balance_reward = torch.mul(self._charge_station.if_balanced(self._device)[0],charge_station_score[:])*100
# print(f"shape_balance:{balance_reward.shape}")
# print(charge_station_score.tolist())
pos_reward = 1.0 / (1.0 + 2.5 * target_dist * target_dist)
self.target_dist = target_dist
self.root_positions = root_positions
self.root_position_reward = torch.zeros_like(self.rew_buf)
# rewards for moving away form starting point
# for i in range(len(self.root_position_reward)):
# self.root_position_reward[i] = sum(root_positions[i][0:3])
self.root_position_reward = torch.tensor([sum(i[0:3]) for i in root_positions], device=self._device)
# print(f"shape_numerator:{numerator.shape}")
numerator = self.root_position_reward*pos_reward+balance_reward
self.rew_buf[:] = torch.div(numerator,1+self.dt_total)
print('REWARDS: ', torch.div(numerator,1+self.dt_total))
def is_done(self) -> None:
# print("line 312")
# These are the dying constaints. It dies if it is going in the wrong direction or starts flying
ones = torch.ones_like(self.reset_buf)
die = torch.zeros_like(self.reset_buf)
die = torch.where(self.target_dist > 20.0, ones, die)
die = torch.where(self.root_positions[..., 2] > 0.5, ones, die)
# die = torch.where(abs(math.atan2(2*self.root_rot[..., 2]*self.root_rot[..., 0] - 2*self.root_rot[1]*self.root_rot[..., 3], 1 - 2*self.root_rot[..., 2]*self.root_rot[..., 2] - 2*self.root_rot[..., 3]*self.root_rot[..., 3])) > math.pi/2, ones, die)
# resets due to episode length
self.reset_buf[:] = torch.where(
self.progress_buf >= self._max_episode_length - 1, ones, die)
# print("line 316")
def simplifiy_angle(current_pos, turn_pos, velocity):
while (abs(current_pos - turn_pos) > math.pi / 2):
if(turn_pos>current_pos):
turn_pos -= math.pi
else:
turn_pos += math.pi
velocity *= -1
return turn_pos, velocity
def calculate_turn_velocity(current_pos, turn_position):
turningspeed = 5.0
setspeed = 0.0
if (current_pos > turn_position+(math.pi/90) or current_pos < turn_position-(math.pi/90)):
setspeed = abs(turn_position-current_pos)/(math.pi/9)
if (setspeed > turningspeed):
setspeed = turningspeed
if (turn_position < current_pos):
setspeed *= -1
return setspeed
def findB(Cx,Cy, angle_change,angle_init=0.463647609,r=1.363107039084):
L= angle_init*r
if(angle_change < 0):
angle_init -= angle_change
else:
angle_init += angle_change
Bx = Cx + r*math.cos(angle_init)
By = Cy + r*math.sin(angle_init)
return Bx, By
def in_charge_station(charge_station_verticies,axle_position, device):
if_in_chargestation = torch.tensor([check_point_2(i, j) for i, j in zip(charge_station_verticies, axle_position)], device=device)
return if_in_chargestation
def check_point(r,m):
def dot(a, b):
return a[0]*b[0] + a[1]*b[1]
# print(len(m))
for i in range(4):
AB = [r[3]-r[1],r[2]-r[0]]
AM = [m[3*i]-r[1],m[3*i + 1]-r[0]]
BC = [r[5]-r[3],r[4]-r[2]]
BM = [m[3*i]-r[3],m[3*i + 1]-r[2]]
dotABAM = dot(AB, AM)
dotABAB = dot(AB, AB)
dotBCBC = dot(BC, BC)
dotBCBM = dot(BC, BM)
out = 0 <= dotABAM and dotABAM <= dotABAB and 0 <= dotBCBM and dotBCBM <= dotBCBC
if out == False:
return 0.0
return 1.0
def check_point_2(r, m):
charge_station = Polygon([(r[0], r[1]), (r[2], r[3]), (r[4], r[5]), (r[6], r[7])])
swerve = Polygon([(m[0], m[1]), (m[4], m[5]), (m[7], m[8]), (m[10], m[11])])
if charge_station.contains(swerve):
return 1.0
return 0.0
| 21,513 | Python | 44.484144 | 256 | 0.611119 |
RoboEagles4828/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/docker/jetson/README.md | # Jetson Docker Image | 21 | Markdown | 20.999979 | 21 | 0.809524 |
RoboEagles4828/offseason2023/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/offseason2023/docker/jetson-isaac-ros/README.md | # Jetson Docker Image with Isaac ROS | 36 | Markdown | 35.999964 | 36 | 0.805556 |
RoboEagles4828/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/offseason2023/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/edna2023/README.md | 
# Requirements
- Ubuntu 22.04
- [Visual Studio Code](https://code.visualstudio.com/)
- RTX Enabled NVIDIA GPU
- (Optional) An Xbox controller
# Installation
### 1. Install Graphics Drivers
Simply run `sudo apt-get install nvidia-driver-525` in order to install the NVIDIA graphics driver for Ubuntu!
### 2. Local Setup
- **Install Docker and Nvidia Docker**
Running `./scripts/local-setup.sh` should install the requirements for this repository to run! At some point during running, it may prompt you for a `ROS_NAMESPACE`, which you can read more about [here](https://docs.ros.org/en/foxy/Tutorials/Intermediate/Launch/Using-ROS2-Launch-For-Large-Projects.html#namespaces). Make sure to restart your machine once the script is done running!
- **Install Remote Development VS Code Extension**
This repository requires the [Remote Development](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.vscode-remote-extensionpack) extension pack. Make sure to install it in the VSCode extensions window!
- **Reopen in Devcontainer**
Once installed, you can open the command pallate by pressing <kbd>F1</kbd>, and running the command `Reopen in Container` in order to open the devcontainer. This might take a while, but once it's finished you should see a message appear in a console stating some helpful commands, along with a list of connected controllers and your `ROS_NAMESPACE` which you set up earlier.
### 3. (Optional) ROS Setup
For the robot to run correctly, both in the simulation and in the real world, we use ROS2 in order to communicate between all of the parts of our project!
- **Building the project**
The entire project is built as a colcon task, so you can run it by pressing <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>B</kbd> in VSCode, or by running `colcon build --symlink-install` in order to build all of the ROS2 packages.
To confirm that this worked, you can simply open a new terminal, and the warning message reminding you to build should be gone!
# Running the Robot
<details><summary><b style="font-size:1.5em">In the simulation</b></summary>
### 1. (Optional) Installing Omniverse Server
Omniverse is a NVIDIA product which allows for programs to cache their information quickly and reliably. It's not needed, but can save a lot on load times!
- **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**
Click on the "Exchange" tab, and search for "Cache", which should return only one result. Nucleus Server should already be installing by default. Wait until both are downloaded and installed before continuing.
### 2. Isaac Container Setup
- **Create Shaders**
Isaac uses RTX heavily in order to accurately render graphics, which takes some powerful shaders. In order to get Isaac to build the shaders, run `isaac-setup` inside the devcontainer in order to start compilation of shaders.
- **Launch Isaac**
In order to actually start the simulation, just run the command `isaac` inside the devcontainer in order to start Isaac. It might take a while on first launch, but you should see the simulation window pop up eventually.
- **Load the robot**
As you should be able to see, there's currently nothing *in* Isaac. It should be showing an empty scene with a popup window to the top left labeled "Import URDF" with a button that says "Load". If you press it, you should see the 2023 playing field appear, along with a brightly colored robot in the center!
### 3. Start the simulation
- **Start Isaac**
Inside of Isaac, you should see a bar with a play button to the left. Click on it, or press <kbd>Space</kbd> in order to start the simulation. If everything works correctly, you should see the robot fall to the ground and be ready for movement!
- **Start the ROS2 Control Node**
In order to get the robot to move around, you're going to need to plug in a controller and start the control node, something that you can do easily by running `launch isaac` inside the devcontainer.
If all goes well, you'll be able to move the robot around with the joystick! See [Controls]() for more details on how to drive the robot.
</details>
<details><summary><b style="font-size:1em">Simulating the RoboRIO</b></summary>
The National Instruments [RoboRIO](https://www.ni.com/en-us/shop/model/roborio.html) is a required computer for the FRC competitions, and as such, all of our code to physically move robot parts has to be run through it.
In order to run this simulator, you'll have to navigate to the `rio/` before running the following commands.
- **Installing RobotPy**
First, run `pip install -r requirements.txt` in order to install robotpy and the other dependencies that the simulator needs.
- **Running the sim**
Once you have the dependencies installed, all you'll have to do is run `python3 robot.py sim` to open the RoboRIO simulator.
To read more on the simulator, check out their docs [here](https://robotpy.readthedocs.io/en/stable/guide/simulator.html)!
</details>
<details><summary><b style="font-size:1.5em">In real life</b></summary>
### 1. Setting up the robot
If you want to actually set up the robot, check out [Setting up the Robot]() in order to get the onboard coprocessor running.
However, for debugging purposes, sometimes its easier to bypass this.
- **Running the Robot**
To run the robot code, make sure you're connected to your robots' network, and run the command `launch real` inside the devcontianer in order to start the robot code.
In order to debug and visualize the robot remotely, we use [rviz](https://github.com/ros2/rviz) in order to view joint poses and other ROS information published from the robot.
- **Starting rviz**
Luckily, we have another quick launch in order to start a preconfigured rviz, so you can simply open a new terminal (separate from the one running `launch real`), and run `launch rviz`. This should open up a new rviz window with the robot inside. You may need to change some of the namespaces in the window, as when running the real robot, the namespace will switch to be `real` instead of whatever you entered in the setup script.
### 2. Driving the Robot
When it comes to driving the robot, you'll need a Driver Station, which we have two separate options to use.
- **NI Driver Station**
In order to run your robot during the competition, you'll need the official National Instruments Driver Station, with all alternatives being disallowed during competitions. For this, you're going to have to have a separate computer running Windows in order to install the [FRC Game Tools](https://www.ni.com/en-us/support/downloads/drivers/download.frc-game-tools.html), which installs the Driver Station as a part of it.
- **Conductor**
Despite the National Instruments driver station being the only officially supported Driver, there are some community made alternatives that you can use! We recommend using [Conductor](https://github.com/Redrield/Conductor), as it's one of the most feature complete community alternatives out there, and runs fully on linux, meaning that you don't need a separate computer, and you can run everything on just one computer!
Once you have a driver station setup, you should be able to enable teleop mode with an Xbox controller connected, and the robot should move when you move the joystick! See [Controls]() for more details on how to drive the robot.
</details>
<details><summary><b style="font-size:1.5em">Debugging the robot</b></summary>
In order to debug the robot, we built our own debugger in Python and PyQT!
### 1. Launching the debugger
Simply run `launch rio-debug` in order to open the debugger!
### 2. Using the debugger
- **Reading in published joint states**
The joint states that are published from the robot to your computer are represented by the slider bars and buttons. Buttons are a togglable state where the output should be one of two values, whereas the sliders are joints where the output should be one of a range of values, usually used for wheels or other motors.
You can tell the current joint state from the robot by looking at the top slider bar, as it will reflect the actual position of the joint on the robot. For the buttons, the color of the button represents the stater of the joint, with green meaning that the state from the robot is the same as the current state from your computer, and yellow meaning that they are not the same.
You can also tell the states of the joints based on the boxes to the left of them, which should contain the exact numbers recieved from ROS.
- **Publishing out your own joint commands**
To publish out your own joint commands, simply use the bottom slider, or click on the buttons in order to edit the joint state being broadcast out to the robot!
</details>
# Gallery



# Setting up your own robot
> An incredibly difficult task which we've only done once or twice. This documentation is currently untested! Here be dragons!
## Requirements
- A National Instruments RoboRIO
- An NVIDIA Jetson Xavier
- A lot of patience
## Setting up the RoboRIO
Because of how our repository is built on the [RobotPy](https://robotpy.readthedocs.io/) framework, you're going to need to install RobotPy.
> Important Note: You'll have to follow these steps on your **host machine**, as there's currently a bug where RobotPy's deployment script does not work inside of the devcontainer.
### 1. Installing RobotPy
Installing robotpy is as simple as navigating to the `rio/` directory and running `pip install -r requirements.txt` in order to install the dependencies of robotpy.
### 2. Installing RobotPy onto the RoboRIO
Unfortunately, this step is somewhat outside of the scope of this tutorial. We recommend you follow RobotPy's [official setup guide](https://robotpy.readthedocs.io/en/stable/install/robot.html) for installing `robotpy-installer` and getting python onto the RIO.
However, there is one thing not covered by the tutorial. You will have to run `robotpy-installer download [package]` and `robotpy-installer install [package]` for the `wpilib` and `rosbags` packages respectively.
### 3. Deploying to the RoboRIO
To deploy to the RoboRIO, you'll need to connect your computer to the RIO, either over USB or over the network. Once you're connected you can run `python3 robot.py deploy` in order to flash the script onto the RoboRIO. | 10,637 | Markdown | 70.878378 | 431 | 0.768638 |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.