ManipulatorControllerComponent.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include "FollowJointTrajectoryActionServer.h"
  9. #include <ROS2/Manipulation/ManipulatorControllerComponent.h>
  10. #include <ROS2/Manipulation/JointPublisherComponent.h>
  11. #include <AzCore/Component/ComponentApplicationBus.h>
  12. #include <AzCore/Component/TransformBus.h>
  13. #include <AzCore/Serialization/EditContext.h>
  14. #include <AzCore/std/functional.h>
  15. #include <PhysX/Joint/PhysXJointRequestsBus.h>
  16. #include <Source/HingeJointComponent.h>
  17. #include <ROS2/Frame/ROS2FrameComponent.h>
  18. namespace ROS2
  19. {
  20. // ManipulatorControllerComponent class
  21. using FollowJointTrajectory = control_msgs::action::FollowJointTrajectory;
  22. ManipulatorControllerComponent::ManipulatorControllerComponent() = default;
  23. ManipulatorControllerComponent::~ManipulatorControllerComponent() = default;
  24. void ManipulatorControllerComponent::Activate()
  25. {
  26. AZ::TickBus::Handler::BusConnect();
  27. m_actionServerClass = AZStd::make_unique<FollowJointTrajectoryActionServer>();
  28. m_actionServerClass->CreateServer(m_ROS2ControllerName);
  29. InitializePid();
  30. }
  31. void ManipulatorControllerComponent::Deactivate()
  32. {
  33. AZ::TickBus::Handler::BusDisconnect();
  34. m_actionServerClass->m_actionServer.reset();
  35. }
  36. void ManipulatorControllerComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required)
  37. {
  38. required.push_back(AZ_CRC_CE("JointPublisherService"));
  39. }
  40. void ManipulatorControllerComponent::Reflect(AZ::ReflectContext* context)
  41. {
  42. if (AZ::SerializeContext* serialize = azrtti_cast<AZ::SerializeContext*>(context))
  43. {
  44. serialize->Class<ManipulatorControllerComponent, AZ::Component>()
  45. ->Version(0)
  46. ->Field("ROS2 Controller name", &ManipulatorControllerComponent::m_ROS2ControllerName)
  47. ->Field("Controller type", &ManipulatorControllerComponent::m_controllerType)
  48. ->Field("PID Configuration Vector", &ManipulatorControllerComponent::m_pidConfigurationVector);
  49. if (AZ::EditContext* ec = serialize->GetEditContext())
  50. {
  51. ec->Class<ManipulatorControllerComponent>("ManipulatorControllerComponent", "[Controller for a robotic arm (only hinge joints)]")
  52. ->ClassElement(AZ::Edit::ClassElements::EditorData, "")
  53. ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game"))
  54. ->Attribute(AZ::Edit::Attributes::Category, "ROS2")
  55. ->DataElement(
  56. AZ::Edit::UIHandlers::Default,
  57. &ManipulatorControllerComponent::m_ROS2ControllerName,
  58. "ROS2 Controller Name",
  59. "It should mirror the name of the ROS2 Controller used as prefix of the ROS2 FollowJointTrajectory Server")
  60. ->DataElement(
  61. AZ::Edit::UIHandlers::ComboBox,
  62. &ManipulatorControllerComponent::m_controllerType,
  63. "Controller type",
  64. "Different controller types to command the joints of the manipulator")
  65. ->EnumAttribute(ManipulatorControllerComponent::Controller::FeedForward, "FeedForward")
  66. ->EnumAttribute(ManipulatorControllerComponent::Controller::PID, "PID")
  67. ->DataElement(
  68. AZ::Edit::UIHandlers::Default,
  69. &ManipulatorControllerComponent::m_pidConfigurationVector,
  70. "PIDs Configuration",
  71. "PID controllers configuration (for all the joints)");
  72. }
  73. }
  74. }
  75. void ManipulatorControllerComponent::InitializePid()
  76. {
  77. for (auto& pid : m_pidConfigurationVector)
  78. {
  79. pid.InitializePid();
  80. }
  81. }
  82. void ManipulatorControllerComponent::InitializeCurrentPosition()
  83. {
  84. auto* jointPublisherComponent = GetEntity()->FindComponent<JointPublisherComponent>();
  85. if (jointPublisherComponent)
  86. {
  87. for (auto & [jointName , hingeComponent] : jointPublisherComponent->GetHierarchyMap())
  88. {
  89. m_jointKeepStillPosition[jointName] = GetJointPosition(hingeComponent);
  90. }
  91. }
  92. }
  93. float ManipulatorControllerComponent::GetJointPosition(const AZ::Component& hingeComponent)
  94. {
  95. float position{0};
  96. auto componentId = hingeComponent.GetId();
  97. auto entityId = hingeComponent.GetEntityId();
  98. const AZ::EntityComponentIdPair id(entityId,componentId);
  99. PhysX::JointRequestBus::EventResult(position, id, &PhysX::JointRequests::GetPosition);
  100. return position;
  101. }
  102. float ManipulatorControllerComponent::ComputeFFJointVelocity(const float currentPosition, const float desiredPosition, const rclcpp::Duration & duration) const
  103. {
  104. // FeedForward (dummy) method
  105. float desiredVelocity = (desiredPosition - currentPosition) / duration.seconds();
  106. return desiredVelocity;
  107. }
  108. float ManipulatorControllerComponent::ComputePIDJointVelocity(const float currentPosition, const float desiredPosition, const uint64_t & deltaTimeNs, int & jointIndex)
  109. {
  110. // PID method
  111. float error = desiredPosition - currentPosition;
  112. float command = m_pidConfigurationVector.at(jointIndex).ComputeCommand(error, deltaTimeNs);
  113. return command;
  114. }
  115. void ManipulatorControllerComponent::SetJointVelocity(AZ::Component& hingeComponent, const float desiredVelocity)
  116. {
  117. auto componentId = hingeComponent.GetId();
  118. auto entityId = hingeComponent.GetEntityId();
  119. const AZ::EntityComponentIdPair id(entityId,componentId);
  120. PhysX::JointRequestBus::Event(id, &PhysX::JointRequests::SetVelocity, desiredVelocity);
  121. }
  122. void ManipulatorControllerComponent::KeepStillPosition([[maybe_unused]] const uint64_t deltaTimeNs)
  123. {
  124. if (!m_keepStillPositionInitialize)
  125. {
  126. InitializeCurrentPosition();
  127. m_keepStillPositionInitialize = true;
  128. }
  129. int jointIndex = 0;
  130. for (auto & [jointName , desiredPosition] : m_jointKeepStillPosition)
  131. {
  132. float currentPosition;
  133. auto* jointPublisherComponent = GetEntity()->FindComponent<JointPublisherComponent>();
  134. if (jointPublisherComponent)
  135. {
  136. currentPosition = GetJointPosition(jointPublisherComponent->GetHierarchyMap()[jointName]);
  137. float desiredVelocity;
  138. if (m_controllerType == Controller::FeedForward)
  139. {
  140. desiredVelocity = ComputeFFJointVelocity(
  141. currentPosition,
  142. desiredPosition,
  143. rclcpp::Duration::from_nanoseconds(5e8)); // Dummy forward time reference
  144. }
  145. else if(m_controllerType == Controller::PID)
  146. {
  147. desiredVelocity = ComputePIDJointVelocity(
  148. currentPosition,
  149. desiredPosition,
  150. deltaTimeNs,
  151. jointIndex);
  152. }
  153. else
  154. {
  155. desiredVelocity = 0.0f;
  156. }
  157. SetJointVelocity(jointPublisherComponent->GetHierarchyMap()[jointName], desiredVelocity);
  158. jointIndex++;
  159. }
  160. }
  161. }
  162. void ManipulatorControllerComponent::ExecuteTrajectory([[maybe_unused]] const uint64_t deltaTimeNs)
  163. {
  164. // If the trajectory is thoroughly executed set the status to Concluded
  165. if (m_trajectory.points.size() == 0)
  166. {
  167. m_initializedTrajectory = false;
  168. m_actionServerClass->m_goalStatus = GoalStatus::Concluded;
  169. AZ_TracePrintf("ManipulatorControllerComponent", "Goal Concluded: all points reached");
  170. return;
  171. }
  172. auto desiredGoal = m_trajectory.points.front();
  173. rclcpp::Duration timeFromStart = rclcpp::Duration(desiredGoal.time_from_start); // arrival time of the current desired trajectory point
  174. rclcpp::Duration threshold = rclcpp::Duration::from_nanoseconds(1e7);
  175. rclcpp::Time timeNow = rclcpp::Time(ROS2::ROS2Interface::Get()->GetROSTimestamp()); // current simulation time
  176. // Jump to the next point if current simulation time is ahead of timeFromStart
  177. if(m_timeStartingExecutionTraj + timeFromStart <= timeNow + threshold)
  178. {
  179. m_trajectory.points.erase(m_trajectory.points.begin());
  180. ExecuteTrajectory(deltaTimeNs);
  181. return;
  182. }
  183. int jointIndex = 0;
  184. for (auto & jointName : m_trajectory.joint_names)
  185. {
  186. auto* jointPublisherComponent = GetEntity()->FindComponent<JointPublisherComponent>();
  187. if (jointPublisherComponent)
  188. {
  189. float currentPosition = GetJointPosition(jointPublisherComponent->GetHierarchyMap()[AZ::Name(jointName.c_str())]);
  190. float desiredPosition = desiredGoal.positions[jointIndex];
  191. float desiredVelocity;
  192. if (m_controllerType == Controller::FeedForward)
  193. {
  194. desiredVelocity = ComputeFFJointVelocity(
  195. currentPosition,
  196. desiredPosition,
  197. m_timeStartingExecutionTraj + timeFromStart - timeNow);
  198. }
  199. else if (m_controllerType == Controller::PID)
  200. {
  201. desiredVelocity = ComputePIDJointVelocity(
  202. currentPosition,
  203. desiredPosition,
  204. deltaTimeNs,
  205. jointIndex);
  206. }
  207. else
  208. {
  209. desiredVelocity = 0.0f;
  210. }
  211. SetJointVelocity(jointPublisherComponent->GetHierarchyMap()[AZ::Name(jointName.c_str())], desiredVelocity);
  212. jointIndex++;
  213. }
  214. }
  215. }
  216. void ManipulatorControllerComponent::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time)
  217. {
  218. const uint64_t deltaTimeNs = deltaTime * 1'000'000'000;
  219. if (m_actionServerClass->m_goalStatus == GoalStatus::Active)
  220. {
  221. if (!m_initializedTrajectory)
  222. {
  223. m_trajectory = m_actionServerClass->m_goalHandle->get_goal()->trajectory;
  224. m_timeStartingExecutionTraj = rclcpp::Time(ROS2::ROS2Interface::Get()->GetROSTimestamp());
  225. m_initializedTrajectory = true;
  226. }
  227. ExecuteTrajectory(deltaTimeNs);
  228. if (m_actionServerClass->m_goalStatus == GoalStatus::Concluded)
  229. {
  230. m_actionServerClass->m_goalStatus = GoalStatus::Pending;
  231. auto result = std::make_shared<FollowJointTrajectory::Result>();
  232. m_actionServerClass->m_goalHandle->succeed(result);
  233. m_keepStillPositionInitialize = false;
  234. }
  235. }
  236. else
  237. {
  238. KeepStillPosition(deltaTimeNs);
  239. }
  240. }
  241. } // namespace ROS2