Robotics StackExchange | Archived questions

How can I publish messages on particular timestamps?

In the tutorial pages we have the classical "talker" publisher node

#!/usr/bin/env python
# license removed for brevity import rospy from std_msgs.msg import String

def talker():
    pub = rospy.Publisher('chatter', String, queue_size=10)
    rospy.init_node('talker', anonymous=True)
    rate = rospy.Rate(10) # 10hz
    while not rospy.is_shutdown():
        hello_str = "hello world %s" % rospy.get_time()
        rospy.loginfo(hello_str)
        pub.publish(hello_str)
        rate.sleep()

if __name__ == '__main__':
    try:
        talker()
    except rospy.ROSInterruptException:
        pass

Here, the talker publish a "hello world" at a rate of 10Hz (???). I don't want that. Suppose that I have a text file "time_stamps.txt" that have a set of lines, each one containing a publication timestamp in the form <timestamp seconds> <timestamp nseconds>

I want to publish "hello world" at the rate that my text file specifies. How can I do this?

Asked by Kansai on 2021-09-07 06:34:14 UTC

Comments

Answers

Hello @Kansai,

I don't know if my answer is right or wrong, but It is working perfect in my case.

Text file: time_stamps.txt

0.1
1
0.01
10
0.01
0.001

My code:

#! /usr/bin/env python

import rospy
from std_msgs.msg import String

rospy.init_node("mynode")
goal_publisher = rospy.Publisher("chatter", String, queue_size=5)

f = open("/home/<FULL PATH FROM HOME TO TXT FILE>/time_stamps.txt", "r")
for i,x in enumerate(f):
    print(i,x)
    rospy.sleep(float(x))
    goal = String()
    goal.data = "Hello World!! "+ x
    goal_publisher.publish(goal)
f.close()

I think this will work, and I am getting every hello world with time given in text file.

Note: If you want to have a delay after msg is publish then rospy.sleep(float(x)) keep this life after your publish or else keep it before.

I think you can also achive the same task using threading.

Asked by Ranjit Kathiriya on 2021-09-07 09:54:51 UTC

Comments

so in this example you are using the values in the text file to delay one publication from the other right? That is an interesting approach. I wonder how can I do something similar but with ros Time values (which is what my timestamps.txt file has)

Asked by Kansai on 2021-09-07 18:09:28 UTC

so in this example you are using the values in the text file to delay one publication from the other right?

Yes,

I wonder how can I do something similar but with ros Time values (which is what my timestamps.txt file has)

I think Taking a ros timer is not a good idea, because the ROS timer is continuously running at a specific time if I try to change the time it is picking the first time and starting running. what I would suggest you should use threading instead.

Asked by Ranjit Kathiriya on 2021-09-08 02:18:30 UTC