Skip to content

Commit

Permalink
[ros2topic] fix pub rate reduced issue
Browse files Browse the repository at this point in the history
Attempt sleep at the specified rate. sleep() takes into account the time elapsed since the last successful sleep().

ref to https://github.com/ros/ros_comm/blob/ros_comm-1.8.15/clients/rospy/src/rospy/timer.py#L62

Signed-off-by: Chris Ye <chris.ye@intel.com>
  • Loading branch information
yechun1 committed Aug 30, 2018
1 parent 4dbd63b commit 96a3d86
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion ros2topic/ros2topic/verb/pub.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,34 @@ def main(args):
args.node_name, 1. / args.rate, args.print, args.once)


_last_time = 0.


def _sleep(period):
"""
Attempt sleep at the specified rate.
sleep() takes into account the time elapsed since
the last successful sleep()
"""
global _last_time
curr_time = time.time()

# detect time jumping backwards
if _last_time > curr_time or _last_time == 0:
_last_time = curr_time

# detect time jumping forwards, as well as loops that are
# inherently too slow
if curr_time - _last_time > period:
_last_time = curr_time

# calculate remaining time
elapsed = curr_time - _last_time
time.sleep(period - elapsed)
_last_time = _last_time + period


def publisher(
message_type, topic_name, values, node_name, period, print_nth, once
):
Expand Down Expand Up @@ -109,6 +137,6 @@ def publisher(
if once:
time.sleep(0.1) # make sure the message reaches the wire before exiting
break
time.sleep(period)
_sleep(period)
node.destroy_node()
rclpy.shutdown()

0 comments on commit 96a3d86

Please sign in to comment.