moveit2
The MoveIt Motion Planning Framework for ROS 2.
Loading...
Searching...
No Matches
demo_pose.cpp
Go to the documentation of this file.
1/*******************************************************************************
2 * BSD 3-Clause License
3 *
4 * Copyright (c) 2023, PickNik Inc.
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions are met:
9 *
10 * * Redistributions of source code must retain the above copyright notice, this
11 * list of conditions and the following disclaimer.
12 *
13 * * Redistributions in binary form must reproduce the above copyright notice,
14 * this list of conditions and the following disclaimer in the documentation
15 * and/or other materials provided with the distribution.
16 *
17 * * Neither the name of the copyright holder nor the names of its
18 * contributors may be used to endorse or promote products derived from
19 * this software without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE
25 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
28 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
29 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 *******************************************************************************/
33
34/* Title : demo_pose.cpp
35 * Project : moveit_servo
36 * Created : 06/07/2023
37 * Author : V Mohammed Ibrahim
38 * Description : Example of controlling a robot through pose commands via the C++ API.
39 */
40
41#include <atomic>
42#include <chrono>
45#include <mutex>
46#include <rclcpp/rclcpp.hpp>
47#include <rclcpp/version.h>
48#include <tf2_geometry_msgs/tf2_geometry_msgs.hpp>
49// For Rolling, Kilted, and newer
50#if RCLCPP_VERSION_GTE(29, 6, 0)
51#include <tf2_ros/transform_listener.hpp>
52// For Jazzy and older
53#else
54#include <tf2_ros/transform_listener.h>
55#endif
57
58using namespace moveit_servo;
59
60namespace
61{
62constexpr auto K_BASE_FRAME = "panda_link0";
63constexpr auto K_TIP_FRAME = "panda_link8";
64} // namespace
65
66int main(int argc, char* argv[])
67{
68 rclcpp::init(argc, argv);
69
70 // The servo object expects to get a ROS node.
71 const rclcpp::Node::SharedPtr demo_node = std::make_shared<rclcpp::Node>("moveit_servo_demo");
72 moveit::setNodeLoggerName(demo_node->get_name());
73
74 // Get the servo parameters.
75 const std::string param_namespace = "moveit_servo";
76 const std::shared_ptr<const servo::ParamListener> servo_param_listener =
77 std::make_shared<const servo::ParamListener>(demo_node, param_namespace);
78 const servo::Params servo_params = servo_param_listener->get_params();
79
80 // The publisher to send trajectory message to the robot controller.
81 rclcpp::Publisher<trajectory_msgs::msg::JointTrajectory>::SharedPtr trajectory_outgoing_cmd_pub =
82 demo_node->create_publisher<trajectory_msgs::msg::JointTrajectory>(servo_params.command_out_topic,
83 rclcpp::SystemDefaultsQoS());
84
85 // Create the servo object
86 const planning_scene_monitor::PlanningSceneMonitorPtr planning_scene_monitor =
87 createPlanningSceneMonitor(demo_node, servo_params);
88 Servo servo = Servo(demo_node, servo_param_listener, planning_scene_monitor);
89
90 // Helper function to get the current pose of a specified frame.
91 const auto get_current_pose = [](const std::string& target_frame, const moveit::core::RobotStatePtr& robot_state) {
92 return robot_state->getGlobalLinkTransform(target_frame);
93 };
94
95 // Wait for some time, so that the planning scene is loaded in rviz.
96 // This is just for convenience, should not be used for sync in real application.
97 std::this_thread::sleep_for(std::chrono::seconds(3));
98
99 // Get the robot state and joint model group info.
100 auto robot_state = planning_scene_monitor->getStateMonitor()->getCurrentState();
101 const moveit::core::JointModelGroup* joint_model_group =
102 robot_state->getJointModelGroup(servo_params.move_group_name);
103
104 // Set the command type for servo.
105 servo.setCommandType(CommandType::POSE);
106
107 // The dynamically updated target pose.
108 PoseCommand target_pose;
109 target_pose.frame_id = K_BASE_FRAME;
110
111 // Initializing the target pose as end effector pose, this can be any pose.
112 target_pose.pose = get_current_pose(K_TIP_FRAME, robot_state);
113
114 // servo loop will exit upon reaching this pose.
115 Eigen::Isometry3d terminal_pose = target_pose.pose;
116 terminal_pose.rotate(Eigen::AngleAxisd(M_PI / 4, Eigen::Vector3d::UnitZ()));
117 terminal_pose.translate(Eigen::Vector3d(0.0, 0.0, -0.1));
118
119 // The target pose (frame being tracked) moves by this step size each iteration.
120 Eigen::Vector3d linear_step_size{ 0.0, 0.0, -0.001 };
121 Eigen::AngleAxisd angular_step_size(0.01, Eigen::Vector3d::UnitZ());
122
123 RCLCPP_INFO_STREAM(demo_node->get_logger(), servo.getStatusMessage());
124
125 rclcpp::WallRate servo_rate(1 / servo_params.publish_period);
126
127 // create command queue to build trajectory message and add current robot state
128 std::deque<KinematicState> joint_cmd_rolling_window;
129 KinematicState current_state = servo.getCurrentRobotState(true /* wait for updated state */);
130 updateSlidingWindow(current_state, joint_cmd_rolling_window, servo_params.max_expected_latency, demo_node->now());
131
132 bool satisfies_linear_tolerance = false;
133 bool satisfies_angular_tolerance = false;
134 bool stop_tracking = false;
135 while (!stop_tracking && rclcpp::ok())
136 {
137 // check if goal reached
138 target_pose.pose = get_current_pose(K_TIP_FRAME, robot_state);
139 satisfies_linear_tolerance |= target_pose.pose.translation().isApprox(terminal_pose.translation(),
140 servo_params.pose_tracking.linear_tolerance);
141 satisfies_angular_tolerance |=
142 target_pose.pose.rotation().isApprox(terminal_pose.rotation(), servo_params.pose_tracking.angular_tolerance);
143 stop_tracking = satisfies_linear_tolerance && satisfies_angular_tolerance;
144
145 // Dynamically update the target pose.
146 if (!satisfies_linear_tolerance)
147 {
148 target_pose.pose.translate(linear_step_size);
149 }
150 if (!satisfies_angular_tolerance)
151 {
152 target_pose.pose.rotate(angular_step_size);
153 }
154
155 // get next servo command
156 KinematicState joint_state = servo.getNextJointState(robot_state, target_pose);
157 StatusCode status = servo.getStatus();
158 if (status != StatusCode::INVALID)
159 {
160 updateSlidingWindow(joint_state, joint_cmd_rolling_window, servo_params.max_expected_latency, demo_node->now());
161 if (const auto msg = composeTrajectoryMessage(servo_params, joint_cmd_rolling_window))
162 {
163 trajectory_outgoing_cmd_pub->publish(msg.value());
164 }
165 if (!joint_cmd_rolling_window.empty())
166 {
167 robot_state->setJointGroupPositions(joint_model_group, joint_cmd_rolling_window.back().positions);
168 robot_state->setJointGroupVelocities(joint_model_group, joint_cmd_rolling_window.back().velocities);
169 }
170 }
171
172 servo_rate.sleep();
173 }
174
175 RCLCPP_INFO_STREAM(demo_node->get_logger(), "REACHED : " << stop_tracking);
176 RCLCPP_INFO(demo_node->get_logger(), "Exiting demo.");
177 rclcpp::shutdown();
178}
void setCommandType(const CommandType &command_type)
Set the type of incoming servo command.
Definition servo.cpp:332
KinematicState getCurrentRobotState(bool block_for_current_state) const
Get the current state of the robot as given by planning scene monitor. This may block if a current ro...
Definition servo.cpp:644
std::string getStatusMessage() const
Get the message associated with the current servo status.
Definition servo.cpp:322
StatusCode getStatus() const
Get the current status of servo.
Definition servo.cpp:317
KinematicState getNextJointState(const moveit::core::RobotStatePtr &robot_state, const ServoInput &command)
Computes the joint state required to follow the given command.
Definition servo.cpp:470
int main(int argc, char *argv[])
Definition demo_pose.cpp:66
std::optional< trajectory_msgs::msg::JointTrajectory > composeTrajectoryMessage(const servo::Params &servo_params, const std::deque< KinematicState > &joint_cmd_rolling_window)
Create a trajectory message from a rolling window queue of joint state commands. Method optionally re...
Definition common.cpp:151
void updateSlidingWindow(KinematicState &next_joint_state, std::deque< KinematicState > &joint_cmd_rolling_window, double max_expected_latency, const rclcpp::Time &cur_time)
Adds a new joint state command to a queue containing commands over a time window. Also modifies the v...
Definition common.cpp:203
planning_scene_monitor::PlanningSceneMonitorPtr createPlanningSceneMonitor(const rclcpp::Node::SharedPtr &node, const servo::Params &servo_params)
Creates the planning scene monitor used by servo.
Definition common.cpp:480
void setNodeLoggerName(const std::string &name)
Call once after creating a node to initialize logging namespaces.
Definition logger.cpp:73
Eigen::Isometry3d pose