SimulationClock.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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 "SimulationClock.h"
  9. #include <AzCore/Time/ITime.h>
  10. #include <ROS2/ROS2Bus.h>
  11. #include <rclcpp/qos.hpp>
  12. namespace ROS2
  13. {
  14. builtin_interfaces::msg::Time SimulationClock::GetROSTimestamp() const
  15. {
  16. const auto elapsedTime = GetElapsedTimeMicroseconds();
  17. builtin_interfaces::msg::Time timeStamp;
  18. timeStamp.sec = static_cast<int32_t>(elapsedTime / 1000000);
  19. timeStamp.nanosec = static_cast<uint32_t>((elapsedTime % 1000000) * 1000);
  20. return timeStamp;
  21. }
  22. int64_t SimulationClock::GetElapsedTimeMicroseconds() const
  23. {
  24. if (auto* timeSystem = AZ::Interface<AZ::ITime>::Get())
  25. {
  26. return static_cast<int64_t>(timeSystem->GetElapsedTimeUs());
  27. }
  28. else
  29. {
  30. AZ_Error("SimulationClock", false, "No ITime interface available for ROS2 Gem simulation clock");
  31. return 0;
  32. }
  33. }
  34. void SimulationClock::Tick()
  35. {
  36. if (!m_clockPublisher)
  37. { // Lazy construct
  38. auto ros2Node = ROS2Interface::Get()->GetNode();
  39. rclcpp::ClockQoS qos;
  40. m_clockPublisher = ros2Node->create_publisher<rosgraph_msgs::msg::Clock>("/clock", qos);
  41. }
  42. rosgraph_msgs::msg::Clock msg;
  43. msg.clock = GetROSTimestamp();
  44. m_clockPublisher->publish(msg);
  45. }
  46. } // namespace ROS2