ros2_control - rolling
Loading...
Searching...
No Matches
joint_trajectory_controller.hpp
1// Copyright (c) 2021 ros2_control Development Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#ifndef JOINT_TRAJECTORY_CONTROLLER__JOINT_TRAJECTORY_CONTROLLER_HPP_
16#define JOINT_TRAJECTORY_CONTROLLER__JOINT_TRAJECTORY_CONTROLLER_HPP_
17
18#include <atomic>
19#include <functional> // for std::reference_wrapper
20#include <memory>
21#include <string>
22#include <vector>
23
24#include "control_msgs/action/follow_joint_trajectory.hpp"
25#include "control_msgs/msg/joint_trajectory_controller_state.hpp"
26#include "control_msgs/msg/speed_scaling_factor.hpp"
27#include "control_msgs/srv/query_trajectory_state.hpp"
28#include "control_toolbox/pid.hpp"
29#include "controller_interface/controller_interface.hpp"
30#include "hardware_interface/loaned_command_interface.hpp"
31#include "hardware_interface/types/hardware_interface_type_values.hpp"
32#include "joint_trajectory_controller/interpolation_methods.hpp"
33#include "joint_trajectory_controller/tolerances.hpp"
34#include "joint_trajectory_controller/trajectory.hpp"
35#include "rclcpp/duration.hpp"
36#include "rclcpp/subscription.hpp"
37#include "rclcpp/time.hpp"
38#include "rclcpp/timer.hpp"
39#include "rclcpp_action/server.hpp"
40#include "rclcpp_lifecycle/state.hpp"
41#include "realtime_tools/realtime_publisher.hpp"
42#include "realtime_tools/realtime_server_goal_handle.hpp"
43#include "realtime_tools/realtime_thread_safe_box.hpp"
44#include "trajectory_msgs/msg/joint_trajectory.hpp"
45#include "trajectory_msgs/msg/joint_trajectory_point.hpp"
46
47// auto-generated by generate_parameter_library
48#include "joint_trajectory_controller/joint_trajectory_controller_parameters.hpp"
49
50using namespace std::chrono_literals; // NOLINT
51
53{
54
56{
57public:
59
61
63
64 controller_interface::return_type update(
65 const rclcpp::Time & time, const rclcpp::Duration & period) override;
66
67 controller_interface::CallbackReturn on_init() override;
68
69 controller_interface::CallbackReturn on_configure(
70 const rclcpp_lifecycle::State & previous_state) override;
71
72 controller_interface::CallbackReturn on_activate(
73 const rclcpp_lifecycle::State & previous_state) override;
74
75 controller_interface::CallbackReturn on_deactivate(
76 const rclcpp_lifecycle::State & previous_state) override;
77
78 controller_interface::CallbackReturn on_error(
79 const rclcpp_lifecycle::State & previous_state) override;
80
81protected:
82 // To reduce number of variables and to make the code shorter the interfaces are ordered in types
83 // as the following constants
84 const std::vector<std::string> allowed_interface_types_ = {
89 };
90
91 // Preallocate variables used in the realtime update() function
92 trajectory_msgs::msg::JointTrajectoryPoint state_current_;
93 trajectory_msgs::msg::JointTrajectoryPoint command_current_;
94 trajectory_msgs::msg::JointTrajectoryPoint command_next_;
95 trajectory_msgs::msg::JointTrajectoryPoint state_desired_;
96 trajectory_msgs::msg::JointTrajectoryPoint state_error_;
97 trajectory_msgs::msg::JointTrajectoryPoint blend_sample_;
98 trajectory_msgs::msg::JointTrajectoryPoint blend_bridge_;
99 // Tracks which controller joints are commanded by a new blended trajectory
100 std::vector<bool> blend_commanded_;
101 // Number of points prepended during a blend (prefix + bridge); used to offset action feedback
102 size_t blend_prefix_size_ = 0;
103
104 // Degrees of freedom
105 size_t dof_;
106 size_t num_cmd_joints_;
107 std::vector<size_t> map_cmd_to_joints_;
108
109 // Storing command joint names for interfaces
110 std::vector<std::string> command_joint_names_;
111
112 // Parameters from ROS for joint_trajectory_controller
113 std::shared_ptr<ParamListener> param_listener_;
114 Params params_;
115 rclcpp::Duration update_period_{0, 0};
116
117 rclcpp::Time traj_time_;
118
119 // variables for storing internal data for open-loop control
120 trajectory_msgs::msg::JointTrajectoryPoint last_commanded_state_;
121 rclcpp::Time last_commanded_time_;
123 rt_last_commanded_state_;
125 interpolation_methods::InterpolationMethod interpolation_method_{
126 interpolation_methods::DEFAULT_INTERPOLATION};
127
128 // The interfaces are defined as the types in 'allowed_interface_types_' member.
129 // For convenience, for each type the interfaces are ordered so that i-th position
130 // matches i-th index in joint_names_
131 template <typename T>
132 using InterfaceReferences = std::vector<std::vector<std::reference_wrapper<T>>>;
133
134 InterfaceReferences<hardware_interface::LoanedCommandInterface> joint_command_interface_;
135 InterfaceReferences<hardware_interface::LoanedStateInterface> joint_state_interface_;
136 std::optional<std::reference_wrapper<hardware_interface::LoanedStateInterface>>
137 scaling_state_interface_;
138 std::optional<std::reference_wrapper<hardware_interface::LoanedCommandInterface>>
139 scaling_command_interface_;
140
141 bool has_position_state_interface_ = false;
142 bool has_velocity_state_interface_ = false;
143 bool has_acceleration_state_interface_ = false;
144 bool has_position_command_interface_ = false;
145 bool has_velocity_command_interface_ = false;
146 bool has_acceleration_command_interface_ = false;
147 bool has_effort_command_interface_ = false;
148
151 using PidPtr = std::shared_ptr<control_toolbox::Pid>;
152 std::vector<PidPtr> pids_;
153 // Feed-forward velocity weight factor when calculating closed loop pid adapter's command
154 std::vector<double> ff_velocity_scale_;
155 // Configuration for every joint if it wraps around (ie. is continuous, position error is
156 // normalized)
157 std::vector<bool> joints_angle_wraparound_;
158 // Preallocated storage for closed-loop PID command output.
159 std::vector<double> closed_loop_pid_command_;
160
161 // If true, enable calculations to stop all joints using constant deceleration
162 bool should_decelerate_on_cancel_ = false;
163 // reserved storage for the max deceleration values
164 std::vector<double> max_decel_;
165 // reserved storage for each joints max stopping time
166 std::vector<double> stop_time_;
167 // reserved storage for each joints hold position at stop
168 std::vector<double> hold_position_;
169 // reserved storage for each joints stop direction
170 std::vector<double> stop_direction_;
171 // reserved storage for the stop trajectory
172 std::shared_ptr<trajectory_msgs::msg::JointTrajectory> stop_trajectory_;
173
174 // Things around speed scaling
175 std::atomic<double> scaling_factor_{1.0};
176 std::atomic<double> scaling_factor_cmd_{1.0};
177
178 // Timeout to consider commands old
179 double cmd_timeout_;
180 // True if holding position or repeating last trajectory point in case of success
181 std::atomic<bool> rt_is_holding_{false};
182 // TODO(karsten1987): eventually activate and deactivate subscriber directly when its supported
183 std::atomic<bool> subscriber_is_active_{false};
184 rclcpp::Subscription<trajectory_msgs::msg::JointTrajectory>::SharedPtr joint_command_subscriber_ =
185 nullptr;
186
187 rclcpp::Service<control_msgs::srv::QueryTrajectoryState>::SharedPtr query_state_srv_;
188
189 std::unique_ptr<Trajectory> current_trajectory_ = nullptr;
191 rt_new_trajectory_msg_;
192
193 std::shared_ptr<trajectory_msgs::msg::JointTrajectory> hold_position_msg_ptr_ = nullptr;
194
195 using ControllerStateMsg = control_msgs::msg::JointTrajectoryControllerState;
197 using StatePublisherPtr = std::unique_ptr<StatePublisher>;
198 rclcpp::Publisher<ControllerStateMsg>::SharedPtr publisher_;
199 StatePublisherPtr state_publisher_;
200 ControllerStateMsg state_msg_;
201
202 using FollowJTrajAction = control_msgs::action::FollowJointTrajectory;
204 using RealtimeGoalHandlePtr = std::shared_ptr<RealtimeGoalHandle>;
205
206 rclcpp_action::Server<FollowJTrajAction>::SharedPtr action_server_;
208 RealtimeGoalHandlePtr rt_active_goal_local_{nullptr};
209 std::atomic<bool> rt_has_pending_goal_{false};
210 rclcpp::TimerBase::SharedPtr goal_handle_timer_;
211 rclcpp::Duration goal_handle_timer_period_ = rclcpp::Duration(50ms);
212
213 // callback for topic interface
214 void topic_callback(const std::shared_ptr<trajectory_msgs::msg::JointTrajectory> msg);
215
216 // Non-RT hook run on every incoming trajectory before validation.
217 void preprocess_incoming_trajectory(trajectory_msgs::msg::JointTrajectory & msg) const;
218 // true if every point has positions but no velocities or accelerations
219 bool is_positions_only(const trajectory_msgs::msg::JointTrajectory & traj) const;
220 // fill time_from_start from positions_upsampling.policy_frequency when timing is absent
221 void synthesize_timing(trajectory_msgs::msg::JointTrajectory & traj) const;
222
223 // callbacks for action_server_
224 rclcpp_action::GoalResponse goal_received_callback(
225 const rclcpp_action::GoalUUID & uuid, std::shared_ptr<const FollowJTrajAction::Goal> goal);
226 rclcpp_action::CancelResponse goal_cancelled_callback(
227 const std::shared_ptr<rclcpp_action::ServerGoalHandle<FollowJTrajAction>> goal_handle);
228 void goal_accepted_callback(
229 std::shared_ptr<rclcpp_action::ServerGoalHandle<FollowJTrajAction>> goal_handle);
230
231 using JointTrajectoryPoint = trajectory_msgs::msg::JointTrajectoryPoint;
232
242 JointTrajectoryPoint & error, const size_t index, const JointTrajectoryPoint & current,
243 const JointTrajectoryPoint & desired) const;
244 // fill trajectory_msg so it matches joints controlled by this controller
245 // positions set to current position, velocities, accelerations and efforts to 0.0
246 void fill_partial_goal(
247 std::shared_ptr<trajectory_msgs::msg::JointTrajectory> trajectory_msg) const;
248 // Fills omitted joints by sampling the active trajectory so they keep their old motion.
249 void fill_omitted_joints_from_old(
250 const std::shared_ptr<trajectory_msgs::msg::JointTrajectory> & trajectory_msg,
251 const rclcpp::Time & new_start);
252 // Blends a new trajectory into the active one in place (Merge-at-Arrival: prefix+bridge+suffix).
253 // Returns false, leaving the message untouched, if it cannot be blended.
254 bool blend_with_active_trajectory(
255 const std::shared_ptr<trajectory_msgs::msg::JointTrajectory> & trajectory_msg,
256 const rclcpp::Time & time);
257 // sorts the joints of the incoming message to our local order
258 void sort_to_local_joint_order(
259 std::shared_ptr<trajectory_msgs::msg::JointTrajectory> trajectory_msg) const;
260 bool validate_trajectory_msg(const trajectory_msgs::msg::JointTrajectory & trajectory) const;
261 void add_new_trajectory_msg(
262 const std::shared_ptr<trajectory_msgs::msg::JointTrajectory> & traj_msg);
263 bool validate_trajectory_point_field(
264 size_t joint_names_size, const std::vector<double> & vector_field,
265 const std::string & string_for_vector_field, size_t i, bool allow_empty) const;
266
267 // the tolerances from the node parameter
268 SegmentTolerances default_tolerances_;
269 // the tolerances used for the current goal
271 // preallocated memory for tolerances used in RT loop
272 SegmentTolerances active_tol_;
273
274 void preempt_active_goal();
275
278 std::shared_ptr<trajectory_msgs::msg::JointTrajectory> set_hold_position();
279
283 std::shared_ptr<trajectory_msgs::msg::JointTrajectory> decelerate_to_hold_position();
284
289 std::shared_ptr<trajectory_msgs::msg::JointTrajectory> set_success_trajectory_point();
290
291 bool reset();
292
293 bool has_active_trajectory() const;
294
295 void publish_state(
296 const rclcpp::Time & time, const JointTrajectoryPoint & desired_state,
297 const JointTrajectoryPoint & current_state, const JointTrajectoryPoint & state_error);
298
299 void read_state_from_state_interfaces(JointTrajectoryPoint & state);
300
306 void update_state_from_command_interfaces(JointTrajectoryPoint & state);
307 bool read_commands_from_command_interfaces(JointTrajectoryPoint & commands);
308
309 void query_state_service(
310 const std::shared_ptr<control_msgs::srv::QueryTrajectoryState::Request> request,
311 std::shared_ptr<control_msgs::srv::QueryTrajectoryState::Response> response);
312
313private:
314 void update_pids();
315
316 bool contains_interface_type(
317 const std::vector<std::string> & interface_type_list, const std::string & interface_type);
318
319 void init_hold_position_msg();
320 void resize_joint_trajectory_point(
321 trajectory_msgs::msg::JointTrajectoryPoint & point, size_t size, double value = 0.0);
322 void resize_joint_trajectory_point_command(
323 trajectory_msgs::msg::JointTrajectoryPoint & point, size_t size, double value = 0.0);
324 void assign_point_from_command_interface(
325 std::vector<double> & trajectory_point_interface,
326 const std::vector<std::reference_wrapper<hardware_interface::LoanedCommandInterface>> &
327 joint_interface);
328
345 bool set_scaling_factor(double scaling_factor);
346
347 using SpeedScalingMsg = control_msgs::msg::SpeedScalingFactor;
348 rclcpp::Subscription<SpeedScalingMsg>::SharedPtr scaling_factor_sub_;
349
358 template <typename T>
359 void assign_interface_from_point(
360 const T & joint_interface, const std::vector<double> & trajectory_point_interface)
361 {
362 for (size_t index = 0; index < num_cmd_joints_; ++index)
363 {
364 if (!joint_interface[index].get().set_value(
365 trajectory_point_interface[map_cmd_to_joints_[index]]))
366 {
367 RCLCPP_ERROR(
368 get_node()->get_logger(),
369 "Failed to set value for joint '%s' in command interface '%s'. ",
370 command_joint_names_[index].c_str(), joint_interface[index].get().get_name().c_str());
371 return;
372 }
373 }
374 }
375};
376
377} // namespace joint_trajectory_controller
378
379#endif // JOINT_TRAJECTORY_CONTROLLER__JOINT_TRAJECTORY_CONTROLLER_HPP_
Definition controller_interface.hpp:27
Definition joint_trajectory_controller.hpp:56
interpolation_methods::InterpolationMethod interpolation_method_
Specify interpolation method. Default to splines.
Definition joint_trajectory_controller.hpp:125
void compute_error_for_joint(JointTrajectoryPoint &error, const size_t index, const JointTrajectoryPoint &current, const JointTrajectoryPoint &desired) const
Definition joint_trajectory_controller.cpp:1599
controller_interface::return_type update(const rclcpp::Time &time, const rclcpp::Duration &period) override
Control step update. Command interfaces are updated based on on reference inputs and current states.
Definition joint_trajectory_controller.cpp:240
std::shared_ptr< trajectory_msgs::msg::JointTrajectory > set_success_trajectory_point()
set last trajectory point to be repeated at success
Definition joint_trajectory_controller.cpp:2238
std::shared_ptr< trajectory_msgs::msg::JointTrajectory > set_hold_position()
set the current position with zero velocity and acceleration as new command
Definition joint_trajectory_controller.cpp:2138
controller_interface::InterfaceConfiguration state_interface_configuration() const override
Get configuration for controller's required state interfaces.
Definition joint_trajectory_controller.cpp:221
controller_interface::InterfaceConfiguration command_interface_configuration() const override
Get configuration for controller's required command interfaces.
Definition joint_trajectory_controller.cpp:201
void update_state_from_command_interfaces(JointTrajectoryPoint &state)
Definition joint_trajectory_controller.cpp:658
bool use_closed_loop_pid_adapter_
If true, a velocity feedforward term plus corrective PID term is used.
Definition joint_trajectory_controller.hpp:150
controller_interface::CallbackReturn on_init() override
Extending interface with initialization method which is individual for each controller.
Definition joint_trajectory_controller.cpp:65
std::shared_ptr< trajectory_msgs::msg::JointTrajectory > decelerate_to_hold_position()
decelerate at constant rate to a holding position with zero velocity and acceleration as new command
Definition joint_trajectory_controller.cpp:2150
Definition realtime_publisher.hpp:56
Definition realtime_server_goal_handle.hpp:57
Definition realtime_thread_safe_box.hpp:68
constexpr char HW_IF_EFFORT[]
Constant defining effort interface name.
Definition hardware_interface_type_values.hpp:27
constexpr char HW_IF_ACCELERATION[]
Constant defining acceleration interface name.
Definition hardware_interface_type_values.hpp:25
constexpr char HW_IF_VELOCITY[]
Constant defining velocity interface name.
Definition hardware_interface_type_values.hpp:23
constexpr char HW_IF_POSITION[]
Constant defining position interface name.
Definition hardware_interface_type_values.hpp:21
Definition interpolation_methods.hpp:25
Configuring what command/state interfaces to claim.
Definition controller_interface_base.hpp:72