Search Unity

  1. Unity Asset Manager is now available in public beta. Try it out now and join the conversation here in the forums.
    Dismiss Notice

Question ros unity clock publisher issue

Discussion in 'Robotics' started by vermahrithik10, Apr 2, 2022.

  1. vermahrithik10

    vermahrithik10

    Joined:
    Jan 10, 2022
    Posts:
    12
    I have been testing ros unity for last 3 months and I found a big problem with ros unity clock. I'm able to make ros unity navigation for ros1 but big issue is that TF can be very sensitive when it comes to timestamps but unity ros clock is not that accurate. Similar issue is raised for ros-sharp: https://github.com/siemens/ros-sharp/issues/91

    I constant get errors like:
    My ros clock publisher (similar to Robotics-Nav2-SLAM-Example):
    Code (CSharp):
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6.  
    7.  
    8. using Unity.Robotics.ROSTCPConnector;
    9. using RosMessageTypes.Rosgraph;
    10.  
    11. using Unity.Robotics.Core;
    12.  
    13. public class ClockPublisher : MonoBehaviour
    14. {
    15.  
    16.   [SerializeField] private string _topicName = "clock";
    17.  
    18.   private float _timeStamp   = 0f;
    19.  
    20.  
    21.  
    22.   private ROSConnection _ros;
    23.   private ClockMsg _message;
    24.   public uint sec , nanosec, temp_sec;
    25.  
    26.   //private uint temp_nanosec;
    27.  
    28.  
    29.   double m_PublishRateHz = 200f;
    30.  
    31.   double m_LastPublishTimeSeconds;
    32.  
    33.   double PublishPeriodSeconds => 1.0f / m_PublishRateHz;
    34.  
    35.   bool ShouldPublishMessage => Clock.FrameStartTimeInSeconds - PublishPeriodSeconds > m_LastPublishTimeSeconds;
    36.  
    37.     void Start()
    38.   {
    39.     // setup ROS
    40.     this._ros = ROSConnection.GetOrCreateInstance();
    41.     this._ros.RegisterPublisher<ClockMsg>(this._topicName);
    42.  
    43.     // this._ros.Subscribe<LogMsg>(sub_topic, get_start_time);
    44.  
    45.     // setup ROS Message
    46.     this._message = new ClockMsg();
    47.     this._message.clock.sec = 0;
    48.     this._message.clock.nanosec = 0;
    49.  
    50.     //temp_sec = sec = 0;
    51.   }
    52.  
    53.  
    54.    
    55.     void PublishMessage()
    56.     {
    57.         // Debug.Log(Time.fixedTime);
    58.         // this._timeStamp = Time.fixedTime;
    59.         // sec = (uint)Math.Truncate(this._timeStamp);
    60.         // nanosec = (uint)( (this._timeStamp - sec)*1e+9);
    61.  
    62.         var publishTime = Clock.time;
    63.  
    64.         sec = (uint)publishTime;
    65.         nanosec = (uint)((publishTime - Math.Floor(publishTime)) * Clock.k_NanoSecondsInSeconds);
    66.  
    67.         // temp_sec++;
    68.         // if (temp_sec >= 1000)
    69.         // {
    70.         //     temp_sec = 0;
    71.         //     sec++;
    72.         // }
    73.  
    74.         // nanosec = temp_sec * 1000000;
    75.  
    76.  
    77.         this._message.clock.sec = sec ;
    78.         this._message.clock.nanosec = nanosec;
    79.         m_LastPublishTimeSeconds = publishTime;
    80.         //m_LastPublishTimeSeconds = Time.fixedTime;
    81.         this._ros.Publish(this._topicName, this._message);
    82.  
    83.  
    84.  
    85.     }
    86.  
    87.     private void Update()
    88.     {
    89.        
    90.        if (ShouldPublishMessage)
    91.         {
    92.             PublishMessage();
    93.         }
    94.  
    95.     }
    96.  
    97. }
    To retrieve clock in other scripts( for pub sensor data):

    Code (CSharp):
    1. void Start()
    2.     {
    3.         clock = GameObject.Find("ROSConnectionPrefab").GetComponent<ClockPublisher>();
    4. }
    5.  
    6. //to access the clock time
    7. this._message.header.stamp.sec = clock.sec;
    8. this._message.header.stamp.nanosec = clock.nanosec;
    Please let me know how to make a proper ros clock as well as how to retrieve that clock data in other scripts.
    I think there should be a proper git docs tutorial on ros unity clock like the ros unity frame. Ros Clock is most important for ros unity to work in synchronize.
     
  2. mrpropellers

    mrpropellers

    Unity Technologies

    Joined:
    Jul 10, 2019
    Posts:
    13
    The times being published by Unity's clock are incredibly accurate, but you may be making bad assumptions about what the time published represents. By default, the example clock publisher publishes the simulation time at the point when the last frame was rendered, not the current wallclock time. This means that executing several clock publishes in the same frame will result in several identical clock messages. For the Nav2-SLAM-Example, this was sufficiently granular since all of our sensors were running in step with the rendering thread. If you are publishing anything during FixedUpdate, however, you may want to have your clock publisher access Time.fixedTimeAsDouble (https://docs.unity3d.com/ScriptReference/Time-fixedTimeAsDouble.html) which reports the time the last physics update occurred. FixedTimeAsDouble is the most accurate and granular time step you can publish to ROS without fudging numbers. In order to ensure your clock publisher's rate is as close to expected as possible, you could check whether to publish in both the Update and FixedUpdate calls, and use Time.realtimeSinceStartupAsDouble (https://docs.unity3d.com/ScriptReference/Time-realtimeSinceStartupAsDouble.html), which is unscaled and measured against current wallclock time, rather than simulation time, to determine whether another clock publish should occur.

    From the looks of that error, though, the problem is likely in how your publishers/subscribers are set up. An "extrapolation into the future" error is not unique to Unity simulation - it will also happen in Gazebo or on a real world robot - and will occur any time a tf lookup executes against a stale TF tree or against a bad timestamp. You may be executing TF lookups against
    Time.now()
    in your subscriber instead of using the timestamp from the sensor message. Or, if you are publishing sensor messages and TF messages with the same timestamp at the same time, you may simply have a race condition where the sensor message is sometimes received by your subscriber before the TF message, and your TF tree hasn't been updated when your subscriber attempts to process the sensor message.

    If it's the latter and not the former, you can fudge things in a number of ways to avoid the error: you can wait a frame to publish your sensor data, you can add code to your subscribers to tell them to wait to process a sensor frame until after you've received the newest clock and tf messages, you could change the clock publisher to publish
    Clock.Now
    instead of
    Clock.time
    (which would be less accurate, but should guarantee you have a clock time which is newer than the sensor timestamp), or you could simply change your TF lookup invocations to allow extrapolation into the future (although this is almost always not a good solution and may just hide upstream problems). The best solution is usually the one recommended in the tutorials (http://wiki.ros.org/tf/Tutorials/tf and Time (Python)) -- you may just need to wait for the TF tree to update before attempting your tf lookup.
     
    vermahrithik10 likes this.
  3. vermahrithik10

    vermahrithik10

    Joined:
    Jan 10, 2022
    Posts:
    12
    @mrpropellers Thanks for answering.
    Lets consider a simple unity ros OdomertryPublisher code

    Code (CSharp):
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using Unity.Burst;
    5. using Unity.Collections;
    6. using UnityEngine;
    7. using UnityEngine.Jobs;
    8. using Unity.Jobs;
    9. using Random = Unity.Mathematics.Random;
    10.  
    11. using Unity.Robotics.ROSTCPConnector;
    12. using Unity.Robotics.ROSTCPConnector.ROSGeometry;
    13. using RosMessageTypes.Nav;
    14. using RosMessageTypes.Geometry;            //contain ros OdometryMsg c# Class
    15. using Unity.Robotics.Core;                // for calling Clock.FrameStartTimeInSeconds variable
    16.  
    17.  
    18.  
    19.  
    20. public class OdomertryPublisher : MonoBehaviour
    21. {
    22.  
    23.     ROSConnection ros;
    24.     ClockPublisher clock;
    25.     private OdometryMsg _message;
    26.  
    27.     public string topicName = "odom";
    28.     public string frameId = "odom";
    29.  
    30.     public GameObject base_link;
    31.  
    32.     ArticulationBody rb;
    33.     private Transform _trans;
    34.     QuaternionMsg ang_pos;
    35.     PointMsg lin_pos;
    36.  
    37.    
    38.     Vector3<FLU> lin_vel, rot_vel;
    39.     Vector3 ang_vel_unity;
    40.  
    41.     public float publishMessageFrequency = 100f;
    42.  
    43.     private float _timeElapsed;
    44.     private float _timeStamp;
    45.     uint sec, nanosec;
    46.     // var publishTime;
    47.  
    48.    
    49.  
    50.     double m_LastPublishTimeSeconds;
    51.  
    52.     double PublishPeriodSeconds => 1.0f / publishMessageFrequency;
    53.  
    54.     bool ShouldPublishMessage => Clock.FrameStartTimeInSeconds - PublishPeriodSeconds > m_LastPublishTimeSeconds;
    55.  
    56.     // Start is called before the first frame update
    57.     void Start()
    58.     {
    59.         clock = GameObject.Find("ROSConnectionPrefab").GetComponent<ClockPublisher>();
    60.         ros = ROSConnection.GetOrCreateInstance();
    61.         ros.RegisterPublisher<OdometryMsg>(topicName);
    62.  
    63.         rb = base_link.GetComponent<ArticulationBody>();
    64.         _trans = base_link.GetComponent<Transform>();
    65.        
    66.     }
    67.  
    68.    
    69.     private void FixedUpdate()
    70.     {
    71.        if (ShouldPublishMessage)
    72.         {
    73.             Publish_Odom();
    74.         }
    75.     }
    76.  
    77.     void Publish_Odom()
    78.     {
    79.         this._message = new OdometryMsg();
    80.         // coverting from unity to ros axis
    81.         ang_pos = base_link.transform.localRotation.To<FLU>();
    82.         lin_pos = base_link.transform.localPosition.To<FLU>();
    83.         rot_vel = (this._trans.InverseTransformDirection(this.rb.angularVelocity).To<FLU>());
    84.         lin_vel = (this._trans.InverseTransformDirection(this.rb.velocity).To<FLU>());
    85.  
    86.        
    87.         this._message.header.stamp.sec = clock.sec;
    88.         this._message.header.stamp.nanosec = clock.nanosec;
    89.         this._message.header.frame_id = frameId;
    90.  
    91.         this._message.child_frame_id = base_link.transform.name;
    92.  
    93.         this._message.pose.pose.position = lin_pos;
    94.  
    95.         this._message.pose.pose.orientation = ang_pos;
    96.  
    97.         this._message.twist.twist.linear = lin_vel;
    98.  
    99.        
    100.         this._message.twist.twist.angular = rot_vel;
    101.  
    102.         ros.Publish(this.topicName, this._message);
    103.  
    104.         this._timeElapsed = 0;
    105.         this._timeStamp = Time.fixedDeltaTime;
    106.  
    107.         m_LastPublishTimeSeconds = Clock.time;
    108.  
    109.        
    110.     }
    111. }
    112.  
    how would you take timestamp message and publish it to ros. I found it quite hard to understand unity ros clock and to access it data and publish correct timestamp. Please help me out.

    As well as its a humble request to unity team to make a proper git page tutorial on how to use unity time from the perspective of ros and publishing ros message with correct timestamp because incorrect timestamp can mess up everything.

    I highly believe that unity has all capability to surpass all present day Ros Simulator (like Gazebo, Coppeliasim, Webots etc) in terms of high graphics realistic scenes. Just there are some basis ros need to be satisfy like ros lightweight sensors, ros publishing frequency etc.
     
    nlunscher-cpr likes this.
  4. mrpropellers

    mrpropellers

    Unity Technologies

    Joined:
    Jul 10, 2019
    Posts:
    13
    Apologies for not seeing this sooner but hopefully this info is better late than not at all:
    1. Change line 62 of your ClockPublisher script from
      var publishTime = Clock.time;
      (time of the start of the frame) to
      var publishTime = Clock.Now;
      (exact wallclock time)
    2. Change line 87's
      Update
      to
      FixedUpdate
    3. In the OdometryPublisher, you will need to use Unity's Time interface, because the clock example in the Nav2SLAMExample does not have an interface for getting the time of the last FixedUpdate. Populate your header with the time returned by Time.fixedTimeAsDouble using the same type of conversion to secs/nsecs that you did in ClockPublisher. This will work fine as long as your simulation is running in realtime.
    We don't have a tutorial for managing simulation time because clock management is not an officially supported feature in our packages yet. I can't (as a rule) provide any transparency into our internal prioritization of feature work, but I can promise as a roboticist that has spent many years working with real-time autonomous systems in simulation, proper clock management is always on my mind :)
     
    ahmedharbi and vermahrithik10 like this.