You can use the same classes that the rostopic tool does to do this. If you import rostopic
, you will find in that package several classes that gather statistics about topics. For example, the ROSTopicHz
class is used to get the publishing rate. You can see how to use these classes by mimicking the functions that call them, such as _rostopic_hz
. Basically, the statistics-gathering class instance is created, the topic of interest is subscribed to, and the callback on the instance of the statistics class is passed to the subscription. Then, after giving some time for messages to be processed, you can call a method of the stats class to get the current result.
Here's an example:
> import rospy, rostopic
> rospy.init_node('blurglesplort')
> r = rostopic.ROSTopicHz(-1)
> s = rospy.Subscriber('/joint_states', rospy.AnyMsg, r.callback_hz, callback_args='/joint_states')
> rospy.sleep(1)
> r.print_hz(['/joint_states'])
average rate: 46.186
min: 0.000s max: 0.103s std dev: 0.03928s window: 643
Note that this is probably not a public API. If so, the API may change without notice.