[ROS Q&A] 170 – How can I perform some actions after the program ends?

[ROS Q&A] 170 - How can i perform some actions after the program ends?

Written by Alberto Ezquerro

30/11/2018

Learn how to trigger an event in order to execute some action when our ROS program ends. This is an answer to the following question on ROS Answers:  https://answers.ros.org/question/309529/how-can-i-perform-some-actions-after-the-program-ends/.

Related Resources

Step 1: Get your development environment ready

Either of the following will do:

  1. Use the ROS Development Studio (ROSDS), an online platform for developing for ROS within a PC browser. Easy-peasy. I’m using this option for this post
    1. Once you log in, click on the New ROSject button to create a project that will host your code. Then Click on Open ROSject to launch the development/simulation environment.
    2. To open a “terminal” on ROSDSpick the Shell app from the Tools menu.
    3. You can find the IDE app on the Tools menu.
  2. You have ROS installed on a local PC. Okay, skip to Step 2.

Next step!

Step 2: Create a package with the code given in the post

1. If you are working on ROSDS, please create a ROSject first, as indicated in Step 1.

2. Open a terminal and create a package that holds the Python code:

user:~$ cd catkin_ws/src
user:~/catkin_ws/src$ catkin_create_pkg test_shutdown rospy
Created file test_shutdown/CMakeLists.txt
Created file test_shutdown/package.xml
Created folder test_shutdown/src
Successfully created files in /home/user/catkin_ws/src/test_shutdown. Please adjust the values in package.xml.
user:~/catkin_ws/src$ cd test_shutdown/src
user:~/catkin_ws/src/test_shutdown/src$ touch test_shutdown.py
user:~/catkin_ws/src/test_shutdown/src$ chmod +x test_shutdown.py

3. Open test_shutdown.py in the IDE and paste in the following code:

#!/usr/bin/env python
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()

try:
    talker()
except rospy.ROSInterruptException:
    rospy.loginfo("TEST")

4. Compile and run the code: go back to the catkin_ws directory and run the following commands

user:~/catkin_ws$ catkin_make
user:~/catkin_ws$ source devel/setup.bash
user:~/catkin_ws$ rospack profile
user:~/catkin_ws$ rosrun test_shutdown test_shutdown.py

(PS: Please run nohup roscore & to start ROS master in the background if you get an error that says “cannot connect to master”)

5. Stop the program with Ctrl + C:

Nothing happened? Yes, nothing happened like the OP explained. The OP expected that the word “TEST” would be printed, but it wasn’t. Let’s fix that next.

Step 3: Modify the code so that it triggers some actions when our ROS program ends

The key tool here is the rospy.on_shutdown() hook, which takes a function that should be called when ROS gets the shutdown signal.

Replace the code in test_shutdown.py with the following code that creates the shutdown hook function and registers it.

#!/usr/bin/env python

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()

def my_shutdown_hook():
    rospy.loginfo("It's shutdown time!")

try:
    rospy.on_shutdown(my_shutdown_hook)
    talker()
except rospy.ROSInterruptException:
    rospy.loginfo("TEST")

Now run the program again and then stop it with Ctrl + C:

user:~/catkin_ws$ rosrun test_shutdown test_shutdown.py
[INFO] [1586198566.464600]: hello world 1586198566.46
[INFO] [1586198566.564763]: hello world 1586198566.56
^C[INFO] [1586198568.326002]: It's shutdown time!

And that was it! Of course, the shutdown hook could perform more useful tasks, like stopping the robot for example.

Extra: Video of the post

Here below you have a “sights and sounds” version of this post, just in case you prefer it that way. Enjoy!

Feedback

Did you like this post? Do you have any questions about the explanations? Whatever the case, please leave a comment on the comments section below, so we can interact and learn from each other.

If you want to learn about other ROS or ROS2 topics, please let us know in the comments area and we will do a video or post about it.


Edited by Bayode Aderinola

Topics: ROS Q&A
Masterclass 2023 batch2 blog banner

Check Out These Related Posts

0 Comments

Submit a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Pin It on Pinterest

Share This